我有两个HashMap<String, Integer>
如何获得值的平均值?
HashMap<String, Integer> map1
map1.put("str1", 7);
map1.put("str2", 4);
HashMap<String, Integer> map2
map2.put("str1", 3);
map2.put("str2", 2);
预期输出为:
("str1") = 5;
("str2") = 3;
我可以按如下方式检索两张地图的总和:
map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));
但是如何使用Java 8检索两张地图的平均值?
更新
根据@的要求,我发布了大部分代码:
HashMap<String, HashMap<String, Double>> map;
HashMap<String, Double> map2 = new HashMap<String, Double>();
map = func1();
map = func2();
map = func3();
for (Entry<String, HashMap<String, Double>> entry : map.entrySet()) {
String key = entry.getKey();
HashMap<String, Double> mp = map.get(key);
mp.forEach((k, v) -> map2.merge(k, v, (t, u) -> (t + u) / 2));
for (Entry<String, Double> entry1 : mp.entrySet()) {
StringfieldName = entry1.getKey();
Double score= entry1.getValue();
System.out.println(fieldName.toString() + " = " + score);
}
}
return map2;
}
答案 0 :(得分:4)
你有没有试过这样做:
map1.forEach((k, v) -> map1.merge(k, v, (t, u) -> (t + u) / 2));
答案 1 :(得分:0)
为什么不完全利用Java 8功能呢?
double avg = Stream.of(map1.values(), map2.values())
.map(set -> set.stream().collect(Collectors.summingInt(Integer::intValue)))
.collect(Collectors.averagingDouble(Integer::doubleValue));