Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java stream List<Map<String,Double>> need average based on the string

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.

like image 480
Hruday Avatar asked Dec 18 '25 06:12

Hruday


1 Answers

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.

like image 185
Naman Avatar answered Dec 19 '25 19:12

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!