如何在java 8中展平地图列表

时间:2015-11-05 20:50:18

标签: java lambda java-8

我有要求我有地图列表

[{Men=1},{Men=2, Women=3},{Women=2,Boys=4}]

现在我需要将它设为flatMap,使其看起来像

Gender=countOfValues

在上面的示例中,输出将是

{Men=3,Women=5,Boys=4}

目前我有以下代码:

private Map<String, Long> getGenderMap(
        List<Map<String, Long>> genderToCountList) {
    Map<String, Long> gendersMap = new HashMap<String, Long>();
    Iterator<Map<String, Long>> genderToCountListIterator = genderToCountList
            .iterator();
    while (genderToCountListIterator.hasNext()) {
        Map<String, Long> genderToCount = genderToCountListIterator.next();
        Iterator<String> genderToCountIterator = genderToCount.keySet()
                .iterator();
        while (genderToCountIterator.hasNext()) {
            String gender = genderToCountIterator.next();
            if (gendersMap.containsKey(gender)) {
                Long count = gendersMap.get(gender);
                gendersMap.put(gender, count + genderToCount.get(gender));
            } else {
                gendersMap.put(gender, genderToCount.get(gender));
            }
        }
    }
    return gendersMap;
}

我们如何使用lambda表达式使用Java8编写这段代码?

1 个答案:

答案 0 :(得分:14)

我不会为此使用任何lambdas,但我使用了Map.merge和方法引用,两者都是在Java 8中引入的。

Map<String, Long> result = new HashMap<>();
for (Map<String, Long> map : genderToCountList)
    for (Map.Entry<String, Long> entry : map.entrySet())
        result.merge(entry.getKey(), entry.getValue(), Long::sum);

您也可以使用Stream s执行此操作:

return genderToCountList.stream().flatMap(m -> m.entrySet().stream())
           .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum));