【集合常用的方法】
1.List判空二种方法:
1.list != null && list.size() != 0;
2.CollectionUtils.isEmpty(list);
2. 获取list某个对象属性值的和
//第一种 计数
long sum1= list.stream().mapToLong(Entity::getId).sum();
list.stream().mapToInt/mapDouble//数据类型不同
//第二种 技术
LongSummaryStatistics statistics= list.stream().mapToLong(entity -> entity .getId())).summaryStatistics();
long sum2 = statistics.getSum();
//其他常用的方法
statistics.getMax();//最大值
statistics.getMin();最小值
statistics.getAverage();平均值
3. 根据list中对象某个属性值分组
//分组
Map<String, List<Entity>> groupMap=list.stream().collect(Collectors.groupingBy(Entity::getId));
//计数
Map<String, Long> countMap=list.stream().collect(Collectors.groupingBy(Entity::getId,Collectors.counting()));
//分组并根据另一个属性计数
Map<String, Long> countMap=list.stream().collect(Collectors.groupingBy(Entity::getId,Collectors.summingInt(Entity::getPrice)));
4. 将list转换为map
//第一种
list.stream().collect(Collectors.toMap(Entity::getId, Entity::getName));
//第二种
list.stream().collect(Collectors.toMap(t -> t.getId()+"#"+t.getPrice(),p -> p.getName())
本文来自博客园,作者:与乐i,转载请注明原文链接:https://www.cnblogs.com/linanana/p/16379251.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现