java List中相同的資料合併到一起

木子小僧發表於2019-01-25

值好最後一天崗,寫個小程式
List<Map<Object,Object>> mapList = new ArrayList<Map<Object,Object>>();
    Map<Object,Object> map = new HashMap<Object,Object>();
    map.put("C","111");
    map.put("NAME","LB");
    Map<Object,Object> map1 = new HashMap<Object,Object>();
    map1.put("C","111");
    map1.put("NAME","LA");
    Map<Object,Object> map2 = new HashMap<Object,Object>();
    map2.put("C","112");
    map2.put("NAME","LC");
    Map<Object,Object> map3 = new HashMap<Object,Object>();
    map3.put("C","112");
    map3.put("NAME","Lh");
    Map<Object,Object> map4 = new HashMap<Object,Object>();
    map4.put("C","113");
    map4.put("NAME","LC");
    Map<Object,Object> map5 = new HashMap<Object,Object>();
    map5.put("C","114");
    map5.put("NAME","LF");
    mapList.add(map);
    mapList.add(map1);
    mapList.add(map2);
    mapList.add(map3);
    mapList.add(map4);
    mapList.add(map5);

    Map<Integer, List<Map<Object,Object>>> mapMap = new HashMap<>();
    for (Map<Object,Object> newMap : mapList){
        List<Map<Object, Object>>  newl = new ArrayList<>();
        // map是否包含此key,若已經包含則新增一個新的數字到對應value集合中
        if (mapMap.containsKey(Integer.valueOf(newMap.get("C").toString()))){
            //mapList.add(Integer.valueOf(newMap.get("C").toString()),newMap);
            mapMap.get(Integer.valueOf(newMap.get("C").toString())).add(newMap);
        }else{
            newl.add(newMap);
            mapMap.put(Integer.valueOf(newMap.get("C").toString()), newl);
        }
    }
    System.out.println(mapMap);
}

 



執行結果:

 

純寫著玩的,不喜勿噴

相關文章