I need the average of the list
List<Measurement> measurements = new ArrayList<>();
Measurement m1 = new Measurement();
Map<String,Double> map1 = new HashMap<>();
map1.put("age",18.0);
map1.put("score",88.0);
map1.put("rating",5.0);
m1.setMetric(map1);
Measurement m2 = new Measurement();
Map<String,Double> map2 = new HashMap<>();
map2.put("age",21.0);
map2.put("score",null);
map2.put("rating",23.0);
m2.setMetric(map2);
Measurement m3 = new Measurement();
Map<String,Double> map3 = new HashMap<>();
map3.put("age",31.0);
map3.put("score",32.0);
map3.put("rating",null );
m3.setMetric(map3);
measurements.add(m1);
measurements.add(m2);
measurements.add(m3);
How do I get the average Age for the above list of maps. Also Average Score by ignoring the null values.
Any help would be really appreciated. I am struggling to fix since 3 days. Thank you in advance.
You can get an average of age as:
Double averageAge = measurements.stream()
.flatMap(a -> a.getMetric().entrySet().stream())
.filter(a -> a.getKey().equals("age"))
.mapToDouble(Map.Entry::getValue)
.average()
.orElse(Double.NaN);
and similarly, averaging score would require an additional filter condition to exclude null values.
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