知乎专栏 |
collect就是一个归约操作,可以接受各种做法作为参数,将流中的元素累积成一个汇总结果:
List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis","Hollis666", "Hello", "HelloWorld", "Hollis"); strings = strings.stream().filter(string -> string.startsWith("Hollis")).collect(Collectors.toList()); System.out.println(strings); //Hollis, HollisChuang, Hollis666, Hollis
最佳替代方案
Stream<String> stream = Stream.of("Apple", "Banana", "Coconut"); List<String> fruits = stream.toList(); fruits.forEach(System.out::println);
连接字符串
Stream<String> stream = Stream.of("https://", "www.netkiller.cn", "/java/index.html"); String url = stream.collect(Collectors.joining()); System.out.println(url);
Set<String> studentNames=students.stream().map(student -> student.getName()).collect(Collectors.toSet());
teeing 收集器已公开为静态方法Collectors::teeing。该收集器将其输入转发给其他两个收集器,然后将它们的结果使用函数合并。
package cn.netkiller.demo; public class Student { public String name; public int score; public Student(String name, int score) { this.name = name; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @Override public String toString() { return "Student [name=" + name + ", score=" + score + "]"; } }
package cn.netkiller.demo; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class Test { public Test() { } public static void main(String[] args) { List<Student> list = Arrays.asList(new Student("Neo", 80), new Student("Tom", 60), new Student("Jerry", 70)); // 平均分 总分 String result = list.stream().collect(Collectors.teeing(Collectors.averagingInt(Student::getScore), Collectors.summingInt(Student::getScore), (s1, s2) -> s1 + ":" + s2)); // 最低分 最高分 String result2 = list.stream().collect(Collectors.teeing(Collectors.minBy(Comparator.comparing(Student::getScore)), Collectors.maxBy(Comparator.comparing(Student::getScore)), (s1, s2) -> s1.orElseThrow() + ":" + s2.orElseThrow())); System.out.println(result); System.out.println(result2); } }