Java 8流收集项目列表的地图 [英] Java 8 stream to collect a Map of List of items
本文介绍了Java 8流收集项目列表的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个地图列表,其中存储了角色和人的名字.例如:
I have a List of Maps which stores the roles and the names of people. For ex:
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
,这将为我提供每个角色的名称列表,即
Role and Name are the Keys of the map.
I want to convert this into a Map<String, List<String>> result
, which will give me a list of names for each role, i.e
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());
这样做不会给我角色的名称列表,而只会给我一个名称.我如何继续收集列表中的元素,然后将其添加到键中?
Doing this way will not give me a list of names for the role, it will give me a single name. How do i keep collecting the elements of the list and then add it to a key ?
用于创建基本结构的Java代码:
Java code to create base structure:
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())));
推荐答案
基于Aomine给出的想法:
Based on the idea given by Aomine:
list.stream()
.map(e -> new AbstractMap.SimpleEntry<>(e.get("Role"), e.get("Name")))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
这篇关于Java 8流收集项目列表的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文