Java 8转换Map <department,list <person =“”>&gt;映射<department,list <string =“”>&gt; </department,> </department,>

时间:2015-01-21 16:02:42

标签: dictionary collections java-8 java-stream

使用Collectors.groupingBy()我可以轻松获得Map<Department, List<Person>> - 这为我提供了属于Person的所有Department个对象:

allPersons.stream().collect(Collectors.groupingBy(Person::getDepartment));

现在我想转换生成的&#39; multimap&#39;所以它包含所有人名称而不是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())));

有没有办法在不使用newMap对象的情况下实现这一目标? 像

这样的东西
final Map<Department, List<String>> newMap = 
                personsByDepartmentMap.stream().someBigMagic();

3 个答案:

答案 0 :(得分:6)

Map<Dept, List<String>> namesInDept
    = peopleInDept.entrySet().stream()
                  .collect(toMap(Map.Entry::getKey, 
                                 e -> e.getValue().stream()
                                                  .map(Person::getName)
                                                  .collect(toList()));

答案 1 :(得分:4)

您可以使用

转换地图
Map<Department, List<String>> result =
    personsByDepartmentMap.entrySet().stream()
      .map(e -> new AbstractMap.SimpleImmutableEntry<>(
        e.getKey(),
        e.getValue().stream().map(Person::getName).collect(Collectors.toList())))
  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

此代码显然存在没有标准Pair类型的事实,但您可以使用static import来改进它。

(更新:)作为Brian Goetz has shown,你可以通过将映射和集合组合成一个步骤来解决这个问题,例如

Map<Department, List<String>> result =personsByDepartmentMap.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        e->e.getValue().stream().map(Person::getName).collect(Collectors.toList())));

但是,我仍然认为在一次操作中从原始List检索地图会更容易:

Map<Department, List<String>> collect = allPersons.stream()
    .collect(Collectors.groupingBy(
        Person::getDepartment,
        Collectors.mapping(Person::getName, Collectors.toList())
    ));

这也将受益于static import s:

Map<Department, List<String>> collect = allPersons.stream().collect(
    groupingBy(Person::getDepartment, mapping(Person::getName, toList())));

答案 2 :(得分:2)

我怀疑您不需要中间Map<Person, List<Department>>类型。如果是这种情况,您可以一步完成所有操作:

Map<Department, List<String>> result = allPersons.stream().collect(
    Collectors.groupingBy(Person::getDepartment,
        Collectors.mapping(Person::getName, Collectors.toList())
    )
);