-2

In this code how can i find the average of double values

public static void iterateMapOfMap() {
    Map<String,Map<String,Double>> hm=new HashMap<>();

    Map<String,Double>innerMap1=new HashMap<>();
    innerMap1.put("Key", 10.00);

    Map<String,Double> innerMap2=new HashMap<>();
    innerMap2.put("Key",20.00);

    Map<String,Double>innerMap3=new HashMap<>();
    innerMap3.put("Key",30.00);

    hm.put("date1",innerMap1);
    hm.put("date2", innerMap2);
    hm.put("date3", innerMap3);

I want average of double values of innerMap1,innerMap2,innerMap3, i.e 10.00+20.00+30.00=60/3=20 how to implement this

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
virat
  • 9
  • 1

1 Answers1

1

First get the sum of Double values in each inner map, and then get the average by using java-8 stream

Double average = hm.values()
                   .stream()
                   .mapToDouble(inMap->inMap.values().stream().reduce(0.0,Double::sum))
                   .average()
                   .orElse(0);   //or orElseThrow()
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98