java lambda 求分组内最大值

可以使用 lambda表达式,比较方便,这里主要想说下思路问题,之前一个时受到数据库的影响,

一个是对api理解程度不够的原因,实现方式见方式一;后来有种恍然大悟的感觉,改成了方式二的实现;
方式一:先分组,组内过滤每一条数据

Map<String, List<UserLog>> collect = list.stream().collect(Collectors.groupingBy(UserLog::getPhone));
Map<String, UserLog> result = new HashMap<>();
collect.keySet().forEach(item -> {UserLog userLog = collect.get(item).stream().max(Comparator.comparing(UserLog::getCreateTime)).get();result.putIfAbsent(item, userLog);});

方式二:利用map的key不重复特点

 Map<String, UserLog> collect1 = list.stream().collect(Collectors.toMap(UserLog::getPhone, item -> item, (v1, v2) -> v1.getCreateTime().getTime() > v2.getCreateTime().getTime() ? v1 : v2));


List<FieldInfo> ffList=new ArrayList<>();

ffList.add(new FieldInfo("A",11));
ffList.add(new FieldInfo("B",2));
ffList.add(new FieldInfo("A",1));


ffList.stream().collect(
                  Collectors.collectingAndThen(Collectors.toMap(FieldInfo::getStrCode, t->t,(v1,v2)->v1.getIntVal()>v2.getIntVal()?v1:v2),
                  m->{
                            List<FieldInfo>tmpPRRInfoList=new ArrayList<>();  
                           for(String strKey:m.keySet())
                      {
                           tmpPRRInfoList.add(m.get(strKey));
                      }
                      return tmpPRRInfoList;
                  }));

 

 
非常棒的各类统计: ***
https://blog.csdn.net/InJavaWeTrust/article/details/123546384







posted @ 2024-02-05 18:16  kelelipeng  阅读(210)  评论(0编辑  收藏  举报