Bogdan
Bogdan

Reputation: 713

Java 8 lambdas to find averages of list of maps

How, with Java-8 streams/lambdas, can I find averages of List of maps by keys?

Example:

List<Map<String, Double>> users = Arrays.asList(
  new HashMap<String, Double>()
    {{
      put("weight", 109.0);
      put("height", 180.2);          
     }},
  new HashMap<String, Double>()
    {{
      put("weight", 59.0);
      put("height", 186.2);          
     }}
 );

 Map<String, Double> statistics = 
 //<MISSED CODE with lambdas> (?)

 System.out.println(statistics);
 //{weight=84.0, height=183.1)

With old good foreachs it's quite simple, I am wondering if that could be achieved with lambdas. The reason I need it is that I am going to use Apache Spark and Java-8 lambdas will be a more standard approach for it.

Upvotes: 7

Views: 429

Answers (1)

Flown
Flown

Reputation: 11740

As Andrew Tobilko said, you should use a proper data structure not Maps.

If you insist on using List<Map<>> then you need to Stream::flatMap the Map::entrySet and use the proper Collectors.


List<Map<String, Double>> users = Arrays.asList(new HashMap<String, Double>() {
  {
    put("weight", 109.0);
    put("height", 180.2);
  }
}, new HashMap<String, Double>() {
  {
    put("weight", 59.0);
    put("height", 186.2);
  }
});

Map<String, Double> statistics = users.stream().flatMap(m -> m.entrySet().stream())
    .collect(
        Collectors.groupingBy(Entry::getKey, Collectors.averagingDouble(Entry::getValue))
    );

System.out.println(statistics);
// {weight=84.0, height=183.2}

Upvotes: 6

Related Questions