有人能解释为什么我们需要第一个聚合操作中的最后一个表达式Collectors.toList(),而不是第二个和第三个表达式吗?
Map<Person.Sex, List<String>> namesByGender =
roster
.stream()
.collect(
Collectors.groupingBy(
Person::getGender,
Collectors.mapping(
Person::getName,
Collectors.toList()))); // why need toList here?
Map<Person.Sex, Integer> totalAgeByGender =
roster
.stream()
.collect(
Collectors.groupingBy(
Person::getGender,
Collectors.reducing(
0,
Person::getAge,
Integer::sum)));
Map<Person.Sex, List<Person>> byGender =
roster
.stream()
.collect(
Collectors.groupingBy(Person::getGender)); //without toList()
发布于 2014-12-06 20:36:26
groupingBy
收集器在Map
中创建条目。Map
包含键值对,所以我们说它是Map<K,V>
。为了分组成一个映射,我们需要一个确定键的方法,我们需要一个收集值的方法。
在第二种情况下,价值的收集是按性别-按性别分列的总年龄-的总和。Map
是Map<Person.Sex, *Integer*>
类型的。这意味着地图的关键是性别,而存储的值是该性别的总年龄。因此,分组需要由Person.Sex
进行,并且集合是通过求和进行的,这意味着集合通过使用对int
返回值的Integer.sum()
方法将其转换为Integer
值来将它们转换为Integer
值。
在第一种情况下,值的收集是按性别列出所有名字。Map
是Map<Person.Sex, *List<String>*>
类型的。这意味着映射的键是性别,而存储该键的值是List
of String
__s (Name)。因此,分组需要由Person.Sex
进行,集合需要列出名称,这意味着集合使用由Collectors.toList()
返回的相应收集器将String
值转换为List<String>
值,将它们收集到列表中。
https://stackoverflow.com/questions/27339592
复制相似问题