简体   繁体   中英

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 ie A_avg = (1+4+4)/3, B_avg=(1+5+7)/3 and so on.

What could be an efficient method to do this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM