package com.cyh.java8; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Demo { private static List<Integer> list = new ArrayList<>(5); @BeforeClass public static void init(){ for (int i = 0; i < 5; i++) { list.add(i); } } /** * filter和findAny方法連用獲取集合中匹配的值 * */ @Test public void findAny(){ Optional<Integer> any = list.stream().filter(x -> x.intValue() == 4).findAny(); Assert.assertTrue(any.isPresent()); if (any.isPresent()){ System.out.println(any.get()); } } /** * anyMatch 方法測試 * 其中至少一個知足條件 */ @Test public void anyMatch(){ Assert.assertTrue(list.stream().anyMatch(x->x.intValue()<2)); } /** * anyMatch 方法測試 * 所有知足條件 */ @Test public void allMatch(){ Assert.assertTrue(list.stream().allMatch(x->x.intValue()<5)); } /** * noneMatch 方法測試 * 所有都不知足條件 */ @Test public void noneMatch(){ Assert.assertTrue(list.stream().noneMatch(x->x.intValue()>5)); } /** * noneMatch 方法測試 * 所有都不知足條件 */ @Test public void optionalInt(){ //將封裝類型轉化爲基本類型 IntStream intStream = list.stream().mapToInt(x->x); int[] ints = intStream.toArray(); //批量轉型 long[] longs = list.stream().mapToInt(x -> x).asLongStream().toArray(); double[] doubles = list.stream().mapToInt(x -> x).asDoubleStream().toArray(); System.out.println(Arrays.toString(ints)); System.out.println(Arrays.toString(longs)); System.out.println(Arrays.toString(doubles)); //將基礎類型劉轉化爲封裝類型流 Stream<Integer> boxed = list.stream().mapToInt(x -> x).boxed(); Integer[] integers = boxed.toArray(Integer[]::new); System.out.println(Arrays.toString(integers)); //OptionalInt 基礎類型option OptionalInt OptionalInt any = list.stream().mapToInt(x -> x).findAny(); System.out.println(any.isPresent()); List<Integer> lst = new ArrayList<>(); OptionalInt any1 = lst.stream().mapToInt(x -> x).findAny(); System.out.println(any1.isPresent()); /** * private static final OptionalInt EMPTY = new OptionalInt(); * * private final boolean isPresent; * private final int value; * * private OptionalInt() { * this.isPresent = false; * this.value = 0; * } * * public static OptionalInt empty() { * return EMPTY; * } * * private OptionalInt(int value) { * this.isPresent = true; * this.value = value; * } * * * public static OptionalInt of(int value) { * return new OptionalInt(value); * } * * 能夠看出OptionalInt並非判斷是否爲0;使用of獲取的對象均爲true */ } }