[英]How to take the average of values of several HashMaps in Array of HashMaps efficiently?
我有一個HashMaps列表
List<Map<String, Object>> arrOfMaps = new ArrayList<>();
所有HashMap都具有相同的鍵,並且所有HashMap中的鍵數均相同。
現在,我想連續獲取HashMap中所有鍵的所有值的平均值。
例如,假設下面是我從HashMaps數組中獲得的HashMaps
arrOfMaps[0]={
A:1,
B:1
}
arrOfMaps[1]={
A:4,
B:5
}
arrOfMaps[2]={
A:4,
B:7
}
.
.
.
我想從3個連續的HashMap中獲得A的平均值,即A_avg =(1 + 4 + 4)/ 3,B_avg =(1 + 5 + 7)/ 3等。
有什么有效的方法可以做到這一點?
您可以使用流找到平均值:
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}
使用flatMap
您將獲得所有傳入地圖的輸入流集。 接下來,您將按字符串鍵groupingBy
並分別使用groupingBy
和averagingInt
通過每個鍵獲取平均值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.