1. 程式人生 > >list中多個map的key相同的value相加

list中多個map的key相同的value相加

將多個map中key相同的value值相加合併成一個map

先將多個map放一個list中

result資料:
[{"town":7,"district":6,"village":23}, {"town":7,"district":6,"village":23}, {"town":7,"district":6,"village":23}, {"town":7,"district":6,"village":23}]
    /**
     * 處理Map資料並求和
     *
     * @param result
     */
    private static void handleData(List<Map<String, Object>> result) {
        Map<String, Object> res = new HashMap<>();
        for (Map<String, Object> map : result) {
            Set<String> keySet = map.keySet();
            // 有了Set集合, 就可以獲取其迭代器。
            for (Iterator<String> it = keySet.iterator(); it.hasNext(); ) {
                String key = it.next();
                // 有了鍵可以通過map集合的get方法獲取其對應的值。
                Object value = map.get(key);
                res.put(key, ConvertUtil.obj2Int(value) + ConvertUtil.obj2Int(res.get(key)));
            }
        }
        System.out.println("合併後的資料:" + res);
    }

執行結果:

合併後的資料:{town=28, district=24, village=92}