Java 8将Map <Department,List <Person >>转换为Map <Department,List <String >>

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)

Bri*_*etz 6

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)


Hol*_*ger 4

您可以使用转换地图

\n\n
Map<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));\n
Run Code Online (Sandbox Code Playgroud)\n\n

这段代码显然受到没有标准Pair类型的影响,但您可以通过使用 s 来改进它static import

\n\n

(更新:)正如Brian Goetz 所展示的那样,您可以在这种特定情况下通过将映射和收集合并到一个步骤中来解决它,例如

\n\n
Map<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())));\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

List然而,我仍然认为\xe2\x80\x99s更容易通过一次操作从原始文件中检索地图:

\n\n
Map<Department, List<String>> collect = allPersons.stream()\n    .collect(Collectors.groupingBy(\n        Person::getDepartment,\n        Collectors.mapping(Person::getName, Collectors.toList())\n    ));\n
Run Code Online (Sandbox Code Playgroud)\n\n

这也将受益于static imports:

\n\n
Map<Department, List<String>> collect = allPersons.stream().collect(\n    groupingBy(Person::getDepartment, mapping(Person::getName, toList())));\n
Run Code Online (Sandbox Code Playgroud)\n