一、实现:对已有对象集合List ,需要获取Persion对象的字段 name分组, 并对年龄age字段值做收集 二、字段分组收集方法 注:由于实际业务只有String类型跟数字类型,所以只对String跟Object两种类型判空
注:由于实际业务只有String类型跟数字类型,所以只对String跟Object两种类型判空
public static Map> groupAndCollectionField(List list, Function groupFunction, Function getFiledFunction) { if (Objects.isNull(list)) { return new HashMap<>(); } //按寄收类型分组, 并收集区号(机场) Map> setMap = list.stream().filter(r-> { K groupValue = groupFunction.apply(r); V filedValue = getFiledFunction.apply(r); //分组判空 boolean groupNull = Objects.isNull(groupValue); if (!groupNull && groupValue instanceof String) { groupNull = ((String) groupValue).length() == 0; } //字段判空 boolean filedNull = Objects.isNull(filedValue); if (filedValue instanceof String) { filedNull = ((String) filedValue).length() == 0; } //分组非空 and 字段非空 返回true; 否则返回false return !groupNull && !filedNull; }) .collect(Collectors.groupingBy(groupFunction, Collectors.mapping(getFiledFunction, Collectors.toSet()))); return setMap; }
//场景1 System.out.println("场景1"); List persionList = new ArrayList<>(); persionList.add(new Persion(1, "李二", null)); persionList.add(new Persion(2, null, 30)); persionList.add(new Persion(3, "王五", 15)); persionList.add(new Persion(4, "陈十一", 11)); //分组并收集字段 Map> setMap = Main.groupAndCollectionField(persionList, Persion::getName, Persion::getAge); //遍历 setMap.entrySet().stream().forEach(r-> System.out.println(String.fORMat("name:%s; age:%s",r.geTKEy(),r.getValue()))); System.out.println(""); //场景2 System.out.println("场景2"); persionList = new ArrayList<>(); persionList.add(new Persion(1, "李二", 22)); persionList.add(new Persion(2, "李二", 30)); persionList.add(new Persion(3, "王五", 15)); persionList.add(new Persion(4, "陈十一", 11)); //分组并收集字段 setMap = Main.groupAndCollectionField(persionList, Persion::getName, Persion::getAge); //遍历 setMap.entrySet().stream().forEach(r-> System.out.println(String.format("name:%s; age:%s",r.getKey(),r.getValue()))); }
来源地址:https://blog.csdn.net/tingyesiyu/article/details/130803702
--结束END--
本文标题: java 对List集合中元素对象按字段分组,并收集指定字段的值
本文链接: https://www.lsjlt.com/news/393149.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0