use*_*745 5 collections dictionary java-8 java-stream
使用Collectors.groupingBy()我可以轻松获得Map<Department, List<Person>>- 这给了我所有的Person对象Department:
allPersons.stream().collect(Collectors.groupingBy(Person::getDepartment));
Run Code Online (Sandbox Code Playgroud)
现在我想转换生成的'multimap',使其包含所有Persons的名称,而不是Person对象.
实现这一目标的一种方法是:
final Map<Department, List<String>> newMap = new HashMap<>();
personsByDepartmentMap.stream
.forEach((d, lp) -> newMap.put(
d, lp.stream().map(Person::getName).collect(Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
有没有办法在不使用newMap对象的情况下实现这一目标?就像是
final Map<Department, List<String>> newMap =
personsByDepartmentMap.stream().someBigMagic();
Run Code Online (Sandbox Code Playgroud)
Map<Dept, List<String>> namesInDept
= peopleInDept.entrySet().stream()
.collect(toMap(Map.Entry::getKey,
e -> e.getValue().stream()
.map(Person::getName)
.collect(toList()));
Run Code Online (Sandbox Code Playgroud)
您可以使用转换地图
\n\nMap<Department, List<String>> result =\n personsByDepartmentMap.entrySet().stream()\n .map(e -> new AbstractMap.SimpleImmutableEntry<>(\n e.getKey(),\n e.getValue().stream().map(Person::getName).collect(Collectors.toList())))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\nRun Code Online (Sandbox Code Playgroud)\n\n这段代码显然受到没有标准Pair类型的影响,但您可以通过使用 s 来改进它static import。
(更新:)正如Brian Goetz 所展示的那样,您可以在这种特定情况下通过将映射和收集合并到一个步骤中来解决它,例如
\n\nMap<Department, List<String>> result =personsByDepartmentMap.entrySet().stream()\n .collect(Collectors.toMap(\n Map.Entry::getKey,\n e->e.getValue().stream().map(Person::getName).collect(Collectors.toList())));\nRun Code Online (Sandbox Code Playgroud)\n\nList然而,我仍然认为\xe2\x80\x99s更容易通过一次操作从原始文件中检索地图:
Map<Department, List<String>> collect = allPersons.stream()\n .collect(Collectors.groupingBy(\n Person::getDepartment,\n Collectors.mapping(Person::getName, Collectors.toList())\n ));\nRun Code Online (Sandbox Code Playgroud)\n\n这也将受益于static imports:
Map<Department, List<String>> collect = allPersons.stream().collect(\n groupingBy(Person::getDepartment, mapping(Person::getName, toList())));\nRun Code Online (Sandbox Code Playgroud)\n