如何在Java 8中拼合地图列表 [英] How to flatten List of Maps in java 8
本文介绍了如何在Java 8中拼合地图列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有地图列表的要求
[{Men=1},{Men=2, Women=3},{Women=2,Boys=4}]
现在我需要将其制作为一个flatMap,使其看起来像
Now I need make it a flatMap such that it looks like
Gender=countOfValues
在上面的示例中,输出为
In the above example the output would be
{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;
}
我们如何使用Java8使用Lambda表达式编写这段代码?
How do we write this piece of code using Java8 using lambda expressions?
推荐答案
我不会为此使用任何lambda,但是我使用了Java 8中引入的Map.merge
和方法引用.
I wouldn't use any lambdas for this, but I have used Map.merge
and a method reference, both introduced in 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执行此操作:
You can also do this with Stream
s:
return genderToCountList.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum));
这篇关于如何在Java 8中拼合地图列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文