I have two HashMap<String, Integer> How can I get the average of the values?
HashMap<String, Integer> map1 = ...
map1.put("str1", 7);
map1.put("str2", 4);
HashMap<String, Integer> map2 = ...
map2.put("str1", 3);
map2.put("str2", 2);
The expected output is:
("str1") = 5;
("str2") = 3;
I am able to retrieve the sum of two maps as follows:
map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));
But how can I retrieve the average of two maps using Java 8?
Update:
At the request of @ I am posting a larger portion 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;
}
Did you tried to do this :
map1.forEach((k, v) -> map1.merge(k, v, (t, u) -> (t + u) / 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With