lambda 分组表达式

lamda分组表达式

 1    // 单条件分组,
 2    Map<String, List<YourBean>> mapByOne = yourBeanList.stream().collect(Collectors.groupingBy(YourBean::getBillDateStr));
 3  
 4    // 分组后,统计每组中数据量
 5    Map<String, Long> count = yourBeanList.stream().collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.counting()));
 6  
 7    // 分组后,求出每组中某属性的平均值
 8    Map<String, Double> avg = yourBeanList.stream().filter(i -> i.getGoodAmount() != null).
 9           collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.averagingDouble(YourBean::getGoodAmount)));
10  
11    // 分组,某属性求和
12    Map<String, Double> sum = yourBeanList.stream().filter(i -> i.getGoodAmount() != null).
13                 collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.summingDouble(YourBean::getGoodAmount)));
14  
15         //对求和的结果集进行从大到小排序
16    Map<String, Double> finalMap = new LinkedHashMap<>();
17    sum.entrySet().stream().sorted(Map.Entry.<String, Double>comparingByValue().reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
18  
19    // 分组后,通过join组成新的map
20    Map<String, String> joinNewMap = yourBeanList.stream().filter(i -> i.getGoodAmount() != null)
21                 .collect(Collectors.groupingBy(YourBean::getBillDateStr,
22                         Collectors.mapping(i -> i.getGoodAmount().toString(), Collectors.joining(", ", "Post titles: [", "]"))));
23    // 2022-04-23
24    // Post titles: [3.0, 1.0, 2.0, 3.0]
25  
26    // 转换分组结果List -> Set
27    Map<String, Set<String>> namesByName = yourBeanList.stream()
28                 .collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.mapping(YourBean::getGoodName, Collectors.toSet())));
29    Set<String> x = namesByCity.keySet();
30  
31    // 两个条件分组
32    Map<String, Map<String, List<YourBean>>> mapByTwo = yourBeanList.stream()
33                 .collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.groupingBy(YourBean::getGoodName)));
34  
35         // 使用java8 stream groupingBy 操作,按日期分组list,将List转化为name的List
36         Map<String, List<String>> mapList = yourBeanList.stream()
37                 .collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.mapping(YourBean::getGoodName, Collectors.toList())));

 

posted @ 2022-04-23 17:27  明天,你好啊  阅读(562)  评论(0编辑  收藏  举报