一个list<Map>里map其中的一个字段的值相同,如何判断这个字段相同,就把这个map的其他字段存入另一个map中
引用:https://www.cnblogs.com/dupengfei-summer/p/9283156.html
1 package util; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 public class ListMapUtil { 9 public static void main(String[] args) { 10 mapData(); 11 } 12 13 public static void mapData() { 14 Map map1 = new HashMap<>(); 15 Map map2 = new HashMap<>(); 16 Map map3 = new HashMap<>(); 17 Map map4 = new HashMap<>(); 18 Map map5 = new HashMap<>(); 19 Map map6 = new HashMap<>(); 20 Map map7 = new HashMap<>(); 21 22 map1.put("maId", 17); 23 map1.put("loginNum", 396); 24 25 map2.put("maId", 17); 26 map2.put("shareGoodsOrderNum", 396); 27 28 map3.put("maId", 39); 29 map3.put("loginNum", 3); 30 31 map4.put("maId", 239); 32 map4.put("loginNum", 1323); 33 34 map5.put("maId", 17); 35 map5.put("orderNum", 1); 36 37 map6.put("maId", 39); 38 map6.put("loginNum", 3); 39 40 map7.put("maId", 17); 41 map7.put("addFamerInfoNum", 24); 42 43 List<Map> list = new ArrayList(); 44 list.add(map1); 45 list.add(map2); 46 list.add(map3); 47 list.add(map4); 48 list.add(map5); 49 list.add(map6); 50 list.add(map7); 51 System.out.println("原本的list" + list); 52 53 //合并相同maid的map成为一个map 54 //获取一个map,判断另一个map中的key有没有相同的,有就合并,合并完后 55 56 for (int i = 0; i < list.size(); i++) { 57 Map map = list.get(i); 58 // 从当前项的下一项开始检查 59 for (int j = i + 1; j < list.size(); j++) { 60 Map<String, Object> childMap = list.get(j); 61 // ID 相等 62 if (null != map.get("maId") & null != childMap.get("maId")) { 63 if (map.get("maId").equals(childMap.get("maId"))) { 64 // 合并,此处需要先 remove 65 list.remove(childMap); 66 map.putAll(childMap); 67 } 68 } 69 70 } 71 } 72 System.out.println("合并后的list:" + list); 73 74 75 } 76 77 }
输出值:
1 原本的list[{maId=17, loginNum=396}, {shareGoodsOrderNum=396, maId=17}, {maId=39, loginNum=3}, {maId=239, loginNum=1323}, {orderNum=1, maId=17}, {maId=39, loginNum=3}, {maId=17, addFamerInfoNum=24}] 2 合并后的list:[{shareGoodsOrderNum=396, orderNum=1, maId=17, loginNum=396, addFamerInfoNum=24}, {maId=239, loginNum=1323}, {maId=39, loginNum=3}]