有人可以解釋爲什麼我們需要在第一個集合操作中的最後一個表達式Collectors.toList(),但不是在第二個和第三個集合操作中?爲什麼在集合操作中需要Collector.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-07 04:27:49
我不完全理解你的問題。這兩個分組中使用了兩個完全不同的下游收集器。第一個執行地圖操作,第二個執行縮小操作。 – isnot2bad 2014-12-07 04:28:33
我看到兩個聚合返回地圖實例,但一個有toList,另一個沒有。所以,這就是爲什麼我想知道toList在第一個聚合操作 – PMH 2014-12-07 04:33:27