-
合并多个map并按key倒叙,相同key的value合并为数组
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<>();
map1.put("2020-11-30", "2020-11-30");
map1.put("2020-11-25", "2020-11-25");
Map<String, String> map2 = new HashMap<>();
map2.put("2020-11-12", "2020-11-12");
map2.put("2020-11-25", "2020-11-2522222222");
Map<String, String> map3 = new HashMap<>();
map3.put("2020-11-06", "2020-11-06");
map3.put("2020-11-25", "2020-11-25333333");
//需要合并的map加入到List里
List<Map> mapList = new ArrayList<>();
mapList.add(map1);
mapList.add(map2);
mapList.add(map3);
System.out.println(mapList);//[{2020-11-25=2020-11-25, 2020-11-30=2020-11-30}, {2020-11-25=2020-11-2522222222, 2020-11-12=2020-11-12}, {2020-11-06=2020-11-06, 2020-11-25=2020-11-25333333}]
//合并map并按key倒叙
Map<Object, List> map = new TreeMap(Comparator.reverseOrder());
for(Map m: mapList){
Iterator it = m.keySet().iterator();
while(it.hasNext()){
Object key = it.next();
if(map.containsKey(key)){
//key已存在,把value加入list中
map.get(key).add(m.get(key));
}else{
//key不存在,把value加入新建list中
List valueList = new ArrayList();
valueList.add(m.get(key));
map.put(key, valueList);
}
}
}
System.out.println(map);//{2020-11-30=[2020-11-30], 2020-11-25=[2020-11-25, 2020-11-2522222222, 2020-11-25333333], 2020-11-12=[2020-11-12], 2020-11-06=[2020-11-06]}
}
-
完结撒花