public static <T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)
应用:根据list中对象某属性进行去重
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("111", 132774, 12, "1"));
studentList.add(new Student("123", 13556, 15, "1"));
studentList.add(new Student("1146", 13165142, 16, "1"));
studentList.add(new Student("111", 136542, 14, "2"));
studentList.add(new Student("141321", 5641542, 15, "2"));
studentList.add(new Student("1454135", 2222542, 15, "2"));
List<Student> collect = studentList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Student::getStuName))),
ArrayList::new));
System.out.println(collect.size());
// 等效处理 此处在treeSet构造方法中传入比较器 可以自定义比较器传入
TreeSet<Student> treeSet = new TreeSet<>(Comparator.comparing(Student::getStuName));
treeSet.addAll(studentList);
List<Student> treeCollect = new ArrayList<>(treeSet);
System.out.println(treeCollect.size());
output
Student{stuName='111', stuId=132774, stuAge=12, classNum='1'}
Student{stuName='1146', stuId=13165142, stuAge=16, classNum='1'}
Student{stuName='123', stuId=13556, stuAge=15, classNum='1'}
Student{stuName='141321', stuId=5641542, stuAge=15, classNum='2'}
Student{stuName='1454135', stuId=2222542, stuAge=15, classNum='2'}
ArrayList(Collection extends E> c)
,所以就是把Collector downstream
的结果再给到Function finisher
去处理,用toCollection收集结果