Java8 groupingBy對map分類求和
阿新 • • 發佈:2020-12-07
根據性別進行彙總,求男女的年齡總和
public static void main(String[] args) {
List<Map<String,String>> arrayList = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
map1.put("gender","女");
map1.put ("age","13");
arrayList.add(map1);
Map<String, String> map2 = new HashMap<>();
map2.put("gender","女");
map2.put("age","11");
arrayList.add(map2);
Map<String, String> map3 = new HashMap<>();
map3.put("gender","男");
map3.put("age","15");
arrayList.add(map3);
Map<String, String> map4 = new HashMap<>();
map4.put("gender","男");
map4.put("age", "11");
arrayList.add(map4);
//方法1
Map<String, DoubleSummaryStatistics> collect = arrayList.stream()
.collect(Collectors.groupingBy(e -> e.get("gender"),
Collectors.summarizingDouble(e -> Double.valueOf(e.get("age")))));
double v1 = collect.get("男").getSum();
double v2 = collect.get("女").getSum();
System.out.println("男性年齡總和:" + v1 + "女性年齡總和:" + v2);
//方法2
Map<String, List<Map<String, String>>> list = arrayList.stream().collect(Collectors.groupingBy(g -> g.get("gender")));
list.forEach((k,vlist)->{
DoubleSummaryStatistics sum = vlist.stream().collect(Collectors.summarizingDouble(e->Double.valueOf(e.get("age"))));
System.out.println(k + "性年齡總和:" + sum.getSum());
});
}