一、实现:对已有对象集合List ,需要获取Persion对象的字段 name分组, 并对年龄age字段值做收集
二、字段分组收集方法
注:由于实际业务只有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