使用 toMap 收集元素
Collector 将元素累积到 Map 中,其中 key 是 Student Id,Value 是 Student Value。
List students = new ArrayList(); students.add(new Student(1,"test1")); students.add(new Student(2,"test2")); students.add(new Student(3,"test3")); Map IdToName = students.stream() .collect(Collectors.toMap(Student::getId, Student::getName)); System.out.println(IdToName);
输出 :
{1=test1, 2=test2, 3=test3}
Collectors.toMap 有另一个实现 Collector> toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction).mergeFunction 主要用于选择新值或者保留旧值,如果在 Map 中添加新成员时重复键列表。
mergeFunction 通常看起来像: (s1, s2) -> s1 保留与重复键对应的值,或者 (s1, s2) -> s2 为重复键放置新值。
显式控制 List 或者 Set 的实现
根据 Collectors#toList() 和 Collectors#toSet() 的文档,不保证返回的 List 或者 Set 的类型、可变性、可序列化性或者线程安全性。
为了显式控制要返回的实现,可以使用 Collectors#toCollection(Supplier) 代替,其中给定的供应商返回一个新的空集合。
//syntax with method reference System.out.println(strings .stream() .filter(s -> s != null && s.length() <= 3) .collect(Collectors.toCollection(ArrayList::new)) ); //syntax with lambda System.out.println(strings .stream() .filter(s -> s != null && s.length() <= 3) .collect(Collectors.toCollection(() -> new LinkedHashSet<>())) );
使用 toList() 和 toSet() 收集
通过使用 Stream 中的元素可以轻松地收集到容器中
Stream.collect 操作:
System.out.println(Arrays .asList("apple", "banana", "pear", "kiwi", "orange") .stream() .filter(s -> s.contains("a")) .collect(Collectors.toList()) ); //prints: [apple, banana, pear, orange]
其他集合实例,例如 Set,可以使用其他 Collectors 内置方法创建。
例如,Collectors.toSet() 将 Stream 的元素收集到 Set 中。
收集元素到集合映射
示例:从 ArrayList 到 Map
List list = new ArrayList<>(); list.add(new Student("Davis", SUBJECT.MATH, 35.0)); list.add(new Student("Davis", SUBJECT.SCIENCE, 12.9)); list.add(new Student("Davis", SUBJECT.GEOGRAPHY, 37.0)); list.add(new Student("Sascha", SUBJECT.ENGLISH, 85.0)); list.add(new Student("Sascha", SUBJECT.MATH, 80.0)); list.add(new Student("Sascha", SUBJECT.SCIENCE, 12.0)); list.add(new Student("Sascha", SUBJECT.LITERATURE, 50.0)); list.add(new Student("Robert", SUBJECT.LITERATURE, 12.0)); Map> map = new HashMap<>(); list.stream().forEach(s -> { map.computeIfAbsent(s.getName(), x -> new ArrayList<>()).add(s.getSubject()); }); System.out.println(map);
输出:
{ Robert=[LITERATURE], Sascha=[ENGLISH, MATH, SCIENCE, LITERATURE], Davis=[MATH, SCIENCE, GEOGRAPHY] }
通过使用 Stream.collect 操作,可以轻松地将 Stream 中的元素收集到容器中:
日期:2020-06-02 22:15:16 来源:oir作者:oir