tank
tank

Reputation: 505

How to take the average of values of several HashMaps in Array of HashMaps efficiently?

I have a List of HashMaps

List<Map<String, Object>> arrOfMaps = new ArrayList<>();

All the HashMaps have the same keys and the number of keys in all the HashMaps is same.

Now, I want to take an average of all the values of all the keys in the HashMap consecutively.

For example, suppose below are my HashMaps which I get from the array of HashMaps

arrOfMaps[0]={
A:1,
B:1
}

arrOfMaps[1]={
A:4,
B:5
}

arrOfMaps[2]={
A:4,
B:7
}

.
.
.

I want to have an average of A from 3 consecutive HashMaps i.e. A_avg = (1+4+4)/3, B_avg=(1+5+7)/3 and so on.

What could be an efficient method to do this?

Upvotes: 1

Views: 251

Answers (1)

Ruslan
Ruslan

Reputation: 6290

You could find the average using stream:

Map<String, Double> average = arrOfMaps.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.groupingBy(Map.Entry::getKey, 
             Collectors.averagingInt(value -> (Integer)(value.getValue()))));

System.out.println(average);  // {A=3.0, B=4.333333333333333}

Using flatMap you are getting stream of entry set for all incoming maps. Next you are grouping by string key and getting the average value by each key using groupingBy and averagingInt respectively

Upvotes: 2

Related Questions