合并Map,key相同value融合(不是相加)
以Person的id为key的map,key如果相同,则合并对象,存入list中
实体类:
@Data public class Person { private String id; private String name; }
测试类:
public class T1 { public static void main(String[] args) { List<Map> list = new ArrayList<>(); Person person = new Person(); person.setId("1"); person.setName("ha"); Person person2 = new Person(); person2.setId("2"); person2.setName("haha"); HashMap<String, Person> oneMap = new HashMap<>(); oneMap.put(person.getId(), person); oneMap.put(person2.getId(), person2); Person person3 = new Person(); person3.setId("1"); person3.setName("hahaha"); Person person4 = new Person(); person4.setId("2"); person4.setName("hahahaha"); HashMap<String, Person> twoMap = new HashMap<>(); twoMap.put(person3.getId(), person3); twoMap.put(person4.getId(), person4); list.add(oneMap); list.add(twoMap); Map m = mapMerge(list); System.out.println(m); } public static Map mapMerge(List<Map> list) { Map<Object, List> map = new HashMap<>(); for (Map m : list) { Iterator<Object> it = m.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); if (!map.containsKey(key)) { List newList = new ArrayList<>(); newList.add(m.get(key)); map.put(key, newList); } else { map.get(key).add(m.get(key)); } } } return map; } }
结果:
{1=[Person(id=1, name=ha), Person(id=1, name=hahaha)], 2=[Person(id=2, name=haha), Person(id=2, name=hahahaha)]}
合并方法方法来自链接:https://blog.csdn.net/qq_24877569/article/details/52187388