Java8lambda表达式的使用

下面list和实体根据自己情况调整

一、通过groupingBy或toMap分组

1、一对多分组groupingBy

Map<String, List<User>> groupBySex = list.stream().collect(Collectors.groupingBy(User::getSex));

2、一对一toMap

Map<String, SigInfo> map= list.stream().collect(Collectors.toMap(SigInfo::getCrossId, s -> s));

Map<String, String> map= list.stream().collect(Collectors.toMap(SigInfo::getCrossId, SigInfo::getSignalId));

3、多个字段分组groupingBy

Map<String, List<AllDeviceInfoVO>> map=list.stream().collect(Collectors.groupingBy(AllDeviceInfoVO -> AllDeviceInfoVO.getLaneId() + '-' + AllDeviceInfoVO.getDevcType()));

Map<String,Map<Integer,List<ContrastVO>>> map=list.stream().collect(Collectors.groupingBy(ContrastVO::getDate,Collectors.groupingBy(ContrastVO::getDirection)));

注意分组的字段不能为空,如果为空,可以先过滤再分组

Map<String, List<AllDeviceInfoVO>> map= list.stream()
                    .filter(item-> StringUtils.isNotBlank(item.getLaneId())).collect(Collectors.groupingBy(AllDeviceInfoVO::getLaneId));

4、分组求和

Map<String, Integer> inspectMap = procureInspectList.stream().collect(Collectors.groupingBy(MaterialInspectRecordVO::getInspectId, Collectors.summingInt(MaterialInspectRecordVO::getInspectCount)));

二、通过filter过滤

完全匹配用equals(),不完全匹配用 indexOf()或contains()

List<User> filterList = userList.stream().filter(a -> a.getJobNumber().equals("201901")).collect(Collectors.toList());

三、求和

1、int类型

int sum= list.stream().mapToInt(User::getAge).sum();

2、Long 类型

long sum= list.stream().mapToLong(InterQueryEntity::getVolume).sum();

3、BigDecimal类型

        BigDecimal sum= list.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);

四、最值

1、最大值

Date max= list.stream().map(DriverViolationVO::getVioTime).max(Date::compareTo).get();

2、最小值

Date min= list.stream().map(DriverViolationVO::getVioTime).min(Date::compareTo).get();

五、排序

1、单字段不为空正序

list.sort(Comparator.comparing(User::getId));

2、单字段不为空倒叙

list.sort(Comparator.comparing(VehicleAnalysisDTO::getVehicleScore).reversed());

3、单字段部分为空--升序时,属性值为空排前面

list.sort(Comparator.comparing(RealTimeMonitor::getPassNum,Comparator.nullsFirst(Integer::compareTo)));

4、单字段部分为空--降序时,属性值为空排到后面

list.sort(Comparator.comparing(RealTimeMonitor::getPassNum,Comparator.nullsFirst(Integer::compareTo)).reversed());

5、多字段排序

list.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));

六、去重

List<AccessVO> distinctList= list.stream().distinct().collect(Collectors.toList());

七、获取list某个字段组装新list

List<Long> idList = list.stream().map(a -> a.getId()).collect(Collectors.toList());

八、批量设置某个值

list.stream().forEach(a -> a.setDelFlag("0"));

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值