使用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();
答案 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())
)
);