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 @   明天,你好啊  阅读(583)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
历史上的今天:
2020-04-23 ThreadLocal 内存泄露分析
点击右上角即可分享
微信分享提示