Get average of Two + HashMap using Java 8
I have two HashMap<String, Integer>
How can I get the average?
HashMap<String, Integer> map1 = ...
map1.put("str1", 7);
map1.put("str2", 4);
HashMap<String, Integer> map2 = ...
map2.put("str1", 3);
map2.put("str2", 2);
Expected Result:
("str1") = 5;
("str2") = 3;
I can get the sum of two cards like this:
map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));
But how do I get the average of two maps using Java 8?
Update:
As @ request, I post most of my code:
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;
}
+3
Little kevin
source
to share
2 answers
Have you tried doing this:
map1.forEach((k, v) -> map1.merge(k, v, (t, u) -> (t + u) / 2));
+5
YCF_L
source
to share
Why not take advantage of Java 8 features?
double avg = Stream.of(map1.values(), map2.values())
.map(set -> set.stream().collect(Collectors.summingInt(Integer::intValue)))
.collect(Collectors.averagingDouble(Integer::doubleValue));
0
Teedeez
source
to share