gpt4 book ai didi

dictionary - Java 8 将 Map> 转换为 Map>

转载 作者:行者123 更新时间:2023-12-03 00:15:37 26 4
gpt4 key购买 nike

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

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

现在我想转换生成的“多重 map ”,以便它包含所有人员的姓名,而不是 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();

最佳答案

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

关于dictionary - Java 8 将 Map<Department, List<Person>> 转换为 Map<Department, List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28071632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com