java stream 根据key去重求和

根据key去重并将key相同的value值相加

先将多个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}]

java 1.8之前版本使用多重遍历,遍历处理如下:

    /**
     * 处理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}

java 1.8引入了lambda表达式和stream,用stream处理如下

private static void handleData(List<Map<String, Object>> result) {
        Map<String, Object> res = new HashMap<>();
        result.stream().forEach(a -> a.keySet().forEach(b -> {
            res.put(b, ConvertUtil.obj2Int(res.get(b)) + ConvertUtil.obj2Int(a.get(b)));
        }));
        System.out.println("合并后的数据:" + res);
    }

运行结果:

合并后的数据:{town=28, district=24, village=92}
    原文作者:banjw
    原文地址: https://blog.csdn.net/banjw_129/article/details/83620132
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞