我有一张地图清单.
List<Map<Integer, String>>
Run Code Online (Sandbox Code Playgroud)
例如,列表中的值
<1, String1>
<2, String2>
<1, String3>
<2, String4>
Run Code Online (Sandbox Code Playgroud)
作为最终结果,我想要一个Map>,就像
<1, <String1, String3>>
<2, <String2, String4>>
Run Code Online (Sandbox Code Playgroud)
我怎样才能在Java中实现这一点.
代码:
List<Map<Integer, String>> genericList = new ArrayList<Map<Integer,String>>();
for(TrackActivity activity : activityMajor){
Map<Integer, String> mapIdResponse = activity.getMapIdResponse();
genericList.add(mapIdResponse);
}
Run Code Online (Sandbox Code Playgroud)
现在这个genericList是输入,从这个列表,基于我想要的相同ID
Map<Integer, List<String>> mapIdResponseList
Run Code Online (Sandbox Code Playgroud)
基本上,要根据ID对String的响应进行分组,在列表中对具有相同id的响应进行分组,然后创建一个以id作为键并将列表作为其值的新映射.
ski*_*iwi 14
您可以使用Java 8执行以下操作:
private void init() {
List<Map<Integer, String>> mapList = new ArrayList<>();
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "String1");
mapList.add(map1);
Map<Integer, String> map2 = new HashMap<>();
map2.put(2, "String2");
mapList.add(map2);
Map<Integer, String> map3 = new HashMap<>();
map3.put(1, "String3");
mapList.add(map3);
Map<Integer, String> map4 = new HashMap<>();
map4.put(2, "String4");
mapList.add(map4);
Map<Integer, List<String>> response = mapList.stream()
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(
Map.Entry::getValue,
Collectors.toList()
)
)
);
response.forEach((i, l) -> {
System.out.println("Integer: " + i + " / List: " + l);
});
}
Run Code Online (Sandbox Code Playgroud)
这将打印:
整数:1/List:[String1,String3]
整数:2/List:[ String2 ,String4]
解释(严重担保),恐怕我无法解释每一个细节,你需要了解的基本知识Stream,并Collectors在Java中8首次推出API:
Stream<Map<Integer, String>>从中获得一个mapList.flatMap运算符,该运算符将流粗略地映射到已存在的流中.Map<Integer, String>为Stream<Map.Entry<Integer, String>>并将它们添加到现有流中,因此现在它也是类型Stream<Map.Entry<Integer, String>>.Stream<Map.Entry<Integer, String>>到一个Map<Integer, List<String>>.Collectors.groupingBy,它Map<K, List<V>>基于分组函数生成Function,在这种情况下映射Map.Entry<Integer, String>到a Integer.Map.Entry::getKey它在a上运行Map.Entry并返回一个Integer.Map<Integer, List<Map.Entry<Integer, String>>>如果我没有做任何额外的处理,我会有一个.Collectors.groupingBy,它必须提供一个收集器.Map.Entry条目映射到它们的String值Map.Entry::getValue.Collectors.toList(),因为我想将它们添加到列表中.Map<Integer, List,String>>.