Java : List中 根據map的某個key去重

執筆記憶的空白發表於2018-07-26

  話不多說,看程式碼和效果

 

     /**
     * 根據map中的某個key 去除List中重複的map
     * @author  shijing
     * @param list
     * @param mapKey
     * @return
     */
    public static List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>> 
           list, String mapKey){
        if (CollectionUtils.isNullOrEmpty(list)) return null;

        //把list中的資料轉換成msp,去掉同一id值多餘資料,保留查詢到第一個id值對應的資料
        List<Map<String, Object>> listMap = new ArrayList<>();
        Map<String, Map> msp = new HashMap<>();
        for(int i = list.size()-1 ; i>=0; i--){
            Map map = list.get(i);
            String id = (String)map.get(mapKey);
            map.remove(mapKey);
            msp.put(id, map);
        }
        //把msp再轉換成list,就會得到根據某一欄位去掉重複的資料的List<Map>
        Set<String> mspKey = msp.keySet();
        for(String key: mspKey){
            Map newMap = msp.get(key);
            newMap.put(mapKey, key);
            listMap.add(newMap);
        }
        return listMap;
    }

測試:

public static void main(String[] args) {
        Map<String, Map> msp = new HashMap<String, Map>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("id", "1123");
        map1.put("name", "張三");
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id", "2");
        map2.put("name", "李四");
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("id", "1123");
        map3.put("name", "王五");
        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("id", "3");
        map4.put("name", "趙六");
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        System.out.println("初始資料:" + list.toString());
        System.out.println("去重之後:" + removeRepeatMapByKey(list,"id"));
    }

結果:

初始資料:[{name=張三, id=1123}, {name=李四, id=2}, {name=王五, id=1123}, {name=趙六, id=3}]
去重之後:[{name=李四, id=2}, {name=趙六, id=3}, {name=張三, id=1123}]

 

 

 

相關文章