一、终止操作列举
循环 forEach
计算 min、max、count、 average
匹配 anyMatch、 allMatch、 noneMatch、findFirst、 findAny
汇聚 reduce
收集器 toArray collect
二、例子演示
2-1 循环 forEach
Arrays.asList("1","2","3","5").stream().forEach(System.out::println);
2-2 计算 min
Integer min = Arrays.asList(1, 3, 4, 61, 1).stream().min((a, b) -> a - b).get();
2-3 计算 max
Integer max = Arrays.asList(1, 3, 4, 61, 1).stream().max((a, b) -> a - b).get();
2-4 计算 count (集合中元素的个数)
long count = Arrays.asList(1, 3, 4, 61, 1).stream().count();
2-5 计算 average
double avg = Arrays.asList(1, 3, 4, 61, 1).stream().mapToLong(x -> Long.valueOf(x + "")).average().getAsDouble();
2-6 匹配 anyMatch
//匹配 anyMatch anyMatch表示,判断的条件里,任意一个元素成功,返回true
boolean b = Arrays.asList(1, 3, 4, 61, 1).stream().anyMatch(x -> x % 2 == 0);
2-7 匹配 allMatch
//匹配 allMatch allMatch表示,判断条件里的元素,所有的都是,返回true
boolean b = Arrays.asList(2, 4, 4, 8, 12).stream().allMatch(x -> x % 2 == 0);
2-8 匹配 noneMatch
//匹配 noneMatch noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
boolean b = Arrays.asList(2, 4, 4, 8, 12).stream().noneMatch(x -> x % 2 != 0);
2-9 匹配 findFirst
//用于返回满足条件的第一个元素
Optional<Integer> first= Arrays.asList(1, 2, 3, 4, 5).stream().filter(x -> x % 2 == 0).findFirst();
2-10 匹配 findAny
//findAny相对于findFirst的区别在于,findAny不一定返回第一个,而是返回任意一个
//实际上对于顺序流式处理而言,findFirst和findAny返回的结果是一样的但是当我们启用并行流式处理的时候,
//查找第一个元素往往会有很多限制,如果不是特别需求,在并行流式处理中使用findAny的性能要比findFirst好。
Optional<Integer> any = Arrays.asList(1, 2, 3, 4, 5).stream().filter(x -> x % 2 == 0).findAny();
2-11 汇聚 reduce
//reduce 根据一定的规则将Stream中的元素进行计算后返回一个唯一的值。
//求和
Integer reduce = Arrays.asList(1, 2, 3, 4, 5).stream().reduce((a, b) -> a + b).get();
2-12 收集器 toArray
Integer[] integers = Arrays.asList(1, 2, 3, 4, 5).stream().filter(x -> x % 2 == 0).toArray(Integer[]::new);
2-13 收集器 collect
List<Integer> collect = Arrays.asList(1, 2, 3, 4, 5).stream().filter(x -> x % 2 == 0).collect(Collectors.toList());