我有一个存储角色和人名的地图列表。例如:
List<Map<String, String>> listOfData
1) Role: Batsman
Name: Player1
2)Role: Batsman
Name: Player2
3)Role: Bowler
Name: Player3
角色和名称是地图的键。我想将其转换为 Map<String, List<String>> result
,这将为我提供每个角色的名称列表,即
k1: Batsman v1: [Player1, Player2]
k2: Bowler v2: [Player3]
listOfData
.stream()
.map(entry -> new AbstractMap.SimpleEntry<>(entry.get("Role"), entry.get("Name"))
.collect(Collectors.toList());
这样做不会给我角色的名字列表,它会给我一个名字。我如何继续收集列表的元素,然后将其添加到键中?
创建基本结构的 Java 代码:
Map<String, String> x1 = ImmutableMap.of("Role", "Batsman", "Name", "Player1");
Map<String, String> y1 = ImmutableMap.of("Role", "Batsman", "Name", "Player2");
Map<String, String> z1 = ImmutableMap.of("Role", "Bowler", "Name", "Player3");
List<Map<String, String>> list = ImmutableList.of(x1, y1, z1);
Map<String, List<String>> z = list.stream()
.flatMap(e -> e.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
原文由 user1692342 发布,翻译遵循 CC BY-SA 4.0 许可协议
基于Aomine给出的思路: