java map <String,String>转Map<String,List>
Map<String,String> map1=new HashMap<>();
map1.put("key1","value1");
map1.put("key2","value2");
Map<String,String> map2=new HashMap<>();
map2.put("key1","value3");
map2.put("key3","value4");
Map<String,String> map3=new HashMap<>();
map3.put("key3","value5");
map3.put("key2","value6");
转换之后的结果为:
Map<String,List<String>> result=new HashMap<>();
<key1,[value1,value3]>
<key2,[value2,value6]>
<key3,[value4,value5]>
核心代码片段
public static Map<String, List<String>> groupByKeyValueAsList(List<Map<String, String>> lists) {
List<String> all = new ArrayList<>();
lists.forEach(item -> {
item.forEach((k, v) -> {
all.add(k + "&" + v);
});
});
Map<String, List<String>> map = all.stream().collect(Collectors.groupingBy(k -> k.split("&")[0]));
Map<String, List<String>> result = new HashMap<>();
map.forEach((k, v) -> {
result.put(k, v.stream().map(i -> i.split("&")[1]).collect(Collectors.toList()));
});
return result;
}