How to add inner elements of Map when keys are duplicate with Java Stream API

陌路散爱 提交于 2019-12-03 17:17:43

You need to use the mergeFunction parameter of the toMap(keyMapper, valueMapper, mergeFunction) collector. This function is called on duplicate values and will merge those two values into a new one.

In this case, we need to merge two maps by summing the values with the same key. The easiest solution to do that is to iterate over all the entries of the second map and merge each entry in the first map. If the mapping does not exist, it will be created with the correct value. If it does, the new value will be the sum of the two current values.

Now, assuming each value is in fact a Double:

finalSalesReportForSoldProperty.stream().collect(Collectors.toMap(
    tags -> ((String) tags.get("assetStatus")).replaceAll("[\\- ]", ""),
    Function.identity(),
    (m1, m2) -> {
        Map<String, Object> map = new HashMap<>(m1);
        m2.entrySet().stream()
                     .filter(e -> e.getValue() instanceof Double)
                     .forEach(e -> map.merge(e.getKey(), e.getValue(), (o1, o2) -> ((Double) o1) + ((Double) o2)));
        return map;
    }
));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!