这是Stream
操做中的最后一步,终止操做,终止操做会从流的流水线生成结果。其结果能够是任何不是流的值,例如:List
,Integer
,void
java
方法名 | 介绍 | 返回类型 |
---|---|---|
allMatch | 检查是否匹配全部元素 | boolean |
anyMatch | 检查是否至少匹配一个元素 | boolean |
noneMatch | 检查是否没有匹配全部元素 | boolean |
findFirst | 返回第一个元素 | Optional |
findAny | 返回当前流中的任意元素 | Optional |
count | 返回流中元素总个数 | |
max | 返回流中最大值 | |
min | 返回流中最小值 |
package java8; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @Description: * @Date: 2020/7/15 00:04 * @Auther: zhaodi */ public class StreamDemo01 { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "赵迪", 23)); studentList.add(new Student(3, "tom", 25)); studentList.add(new Student(2, "tom", 27)); studentList.add(new Student(2, "rose", 22)); Comparator<Student> comparator = Comparator.comparingInt(Student::getId); List<Student> list = studentList.stream().sorted(comparator).collect(Collectors.toList()); System.out.println(list); Boolean success = list.stream().allMatch(x -> x.getId() > 1); System.out.println(success); // false Boolean success1 = list.stream().anyMatch(x -> x.getId() > 2); System.out.println(success1); // true Boolean success2 = list.stream().noneMatch(x -> x.getId() == 2); System.out.println(success2);//false Optional<Student> op = list.stream().sorted(comparator).findFirst(); Student student = op.get(); System.out.println(student); Optional<Student> optional = list.stream().findAny(); long count = list.stream().count(); System.out.println(count); Optional<Student> opMax = list.stream().max(comparator); Optional<Student> opMin = list.stream().min(comparator); } }
方法名 | 介绍 | 返回类型 |
---|---|---|
reduce(BinaryOperator b) | 能够将流中元素反复结合起来,获得一个Optional对象 | Option
|
reduce(T iden,BinaryOperator b) | 能够将流中元素反复结合起来,获得一个值 | T |
reduce
方法很是的通用,后面介绍的count
,sum
等均可以使用其实现。reduce
方法有三个重载的方法,本文介绍两个最经常使用的,最后一个留给读者本身学习。先来看reduce
方法的第一种形式,其方法定义以下ide
第一种函数
Optional<T> reduce(BinaryOperator<T> accumulator);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Optional<Integer> optional= list.stream().reduce((x, y) -> x + y); System.out.println(optional.get()); // 45
能够看到reduce
方法接受一个函数,这个函数有两个参数,第一个参数是上次函数执行的返回值(也称为中间结果),第二个参数是stream
中的元素,这个函数把这两个值相加,获得的和会被赋值给下次执行这个函数的第一个参数。要注意的是:第一次执行的时候第一个参数的值是Stream的第一个元素,第二个参数是Stream的第二个元素。这个方法返回值类型是Optional
,这是Java8
防止出现NPE
的一种可行方法,后面的文章会详细介绍,这里就简单的认为是一个容器,其中可能会包含0个或者1个对象学习
第二种code
T reduce(T identity, BinaryOperator<T> accumulator);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Integer sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println(sum);
这个定义上上面已经介绍过的基本一致,不一样的是:它容许用户提供一个循环计算的初始值,若是Stream
为空,就直接返回该值。并且这个方法不会返回Optional
,由于其不会出现null
值对象
如上面代码所示:接口
若是list
集合里面没有一个对象的话,那么第一种写法会报错,第二种结果则是0ip
备注get
map
和reduce
的链接一般称为map-reduce
模式,例如string
List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "赵迪", 23)); studentList.add(new Student(3, "tom", 25)); studentList.add(new Student(2, "tom", 27)); studentList.add(new Student(2, "rose", 22)); Optional sum = studentList.stream().map(x -> x.getAge()).reduce((x, y) -> x + y);
方法名 | 介绍 | 返回类型 |
---|---|---|
collect(Collector c) |
将流转换为其它形式。接受一个Collector 接口的实现,用于给Stream 中元素作汇总方法 |
Collector
接口中的方法的实现决定了如何对流执行收集操做(如收集到List
、Set
、Map
)。
可是Collectors
实现类提供了不少静态方法,能够方便的建立常见收集器实例,具体方法和实例以下
方法名 | 介绍 | 返回类型 |
---|---|---|
Collectors.toList() |
将流转换为List
|
List<T> |
Collectors.toSet() |
将流转换为Set
|
Set<T> |
Collectors.toCollection(LinkedList::new) |
将流转换为集合 | |
Collectors.toMap(Student::getName, Student::getAge, (e, r) -> r) |
转为Map,具体见下面代码 | Map<String,Object> |
Collectors.counting() |
统计个数 | Long |
Collectors.averagingDouble(Student::getAge) |
求平均值 | Double |
Collectors.summingInt(Student::getAge) |
求和 | Integer |
Collectors.maxBy(Comparator c) |
最大值 | Optional<T> |
Collectors.minBy(Comparator c) |
最小值 | Optional<T> |
Collectors.groupingBy(Student::getName) |
单个分组 | Map<String,List<T> |
Collectors.partitioningBy(x->x.getAge()>26) |
分区 | Map<Boolean>,List<T> |
Collectors.summarizingDouble(Student::getAge) |
统计分析 | DoubleSummaryStatistics |
package java8; import java.util.*; import java.util.stream.Collectors; /** * @Description: * @Date: 2020/7/15 00:04 * @Auther: zhaodi */ public class StreamDemo01 { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "赵迪", 23)); studentList.add(new Student(3, "tom", 25)); studentList.add(new Student(2, "tom", 27)); studentList.add(new Student(2, "rose", 22)); // 转List List<Student> newList = studentList.stream().filter(x -> x.getAge() > 23).collect(Collectors.toList()); System.out.println(newList); //[Student(id=3, name=tom, age=25), Student(id=2, name=tom, age=27)] // 转Set Set<Student> studentSet = studentList.stream().collect(Collectors.toSet()); System.out.println(studentSet);//[Student(id=3, name=tom, age=25), Student(id=2, name=rose, age=22), Student(id=1, name=赵迪, age=23), Student(id=2, name=tom, age=27)] // 转集合 studentList.stream().collect(Collectors.toCollection(LinkedList::new)); // 转Map(e:旧的key,r:新的key,若是存在key重复,则使用新的key或者旧的key均可以) Map<String, Object> studentMap = studentList.stream().collect(Collectors.toMap(Student::getName, Student::getAge, (e, r) -> r)); System.out.println(studentMap); // {tom=27, 赵迪=23, rose=22} // 求个数 Long count = studentList.stream().collect(Collectors.counting()); System.out.println(count); // 平均值 Double avgAge = studentList.stream().collect(Collectors.averagingDouble(Student::getAge)); System.out.println(avgAge); // 求和 Integer ageSum = studentList.stream().collect(Collectors.summingInt(Student::getAge)); System.out.println(ageSum); // 最大值 Comparator<Student> ageComparator = Comparator.comparingInt(Student::getAge); Optional<Student> maxStu = studentList.stream().collect(Collectors.maxBy(ageComparator)); System.out.println(maxStu.get()); // 最小值 Optional<Integer> min = studentList.stream().map(Student::getAge).collect(Collectors.minBy(Integer::compare)); System.out.println(min.get()); // 单个分组(根据姓名分组) Map<String, List<Student>> stringListMap = studentList.stream().collect(Collectors.groupingBy(Student::getName)); System.out.println(stringListMap);//{tom=[Student(id=3, name=tom, age=25), Student(id=2, name=tom, age=27)], 赵迪=[Student(id=1, name=赵迪, age=23)], rose=[Student(id=2, name=rose, age=22)]} // 多级分组(先根据姓名分,在根据年纪分) Map<String, Map<Object, List<Student>>> map = studentList.stream().collect(Collectors.groupingBy(Student::getName, Collectors.groupingBy((x) -> { if (x.getAge() > 26) { return "老年"; } else { return "青年"; } }))); System.out.println(map);//{tom={青年=[Student(id=3, name=tom, age=25)], 老年=[Student(id=2, name=tom, age=27)]}, 赵迪={青年=[Student(id=1, name=赵迪, age=23)]}, rose={青年=[Student(id=2, name=rose, age=22)]}} // 分区(分为两个区,年纪大于26和小于等于26) Map<Boolean,List<Student>> partitionStudent = studentList.stream().collect(Collectors.partitioningBy(x->x.getAge()>26)); System.out.println(partitionStudent); //{false=[Student(id=1, name=赵迪, age=23), Student(id=3, name=tom, age=25), Student(id=2, name=rose, age=22)], true=[Student(id=2, name=tom, age=27)]} // 统计分析 DoubleSummaryStatistics dss = studentList.stream().collect(Collectors.summarizingDouble(Student::getAge)); System.out.println(dss.getAverage()); System.out.println(dss.getSum()); System.out.println(dss.getMax()); // 链接 String names = studentList.stream().map(Student::getName).collect(Collectors.joining(",")); System.out.println(names); //赵迪,tom,tom,rose } }