List中常用的Lambda表达式

开发随手记一些常用的吧。

 对list进行循环

对比平常的for循环,stream().forEach可以进行并发处理,比如你这个循环里要进行很多业务处理,调用接口或者第三方,或者查询之类的接口,一般对值的处理还是用for循环好一点,性能上会快一点

  list.stream().forEach(o -> {
                o.setRfm(o.getRfm());
            });

 对list对象某个字段进行条件筛选

list = list.stream().filter(o->o.getRfm().equals(salesPrecisionMarketingVo.getRfm())).collect(Collectors.toList());

取出list对象中的某个字段进行累加

BigDecimal totalAmount =   detailsList.stream()
        // 将对象的amount取出来map为Bigdecimal
        .map(SalesOrderPrecisionMarketingVo::getAmount)
        // 使用reduce()聚合函数,实现累加器
        .reduce(BigDecimal.ZERO,BigDecimal::add);

求list某个数字值最大、最小、和、平均值

list.stream().mapToDouble(User::getAge).sum()//和
list.stream().mapToDouble(User::getAge).max()//最大
list.stream().mapToDouble(User::getAge).min()//最小
list.stream().mapToDouble(User::getAge).average()//平均值

根据list对象某个字段进行排序

其中 reversed() 表示倒序的意思,如果不使用此方法则是正序。

//根据 R 值排序
List<SalesPrecisionMarketingVo> rList = list.stream().sorted(Comparator.comparing(SalesPrecisionMarketingVo::getDeliverySection).reversed()).collect(Collectors.toList());

或者

//降序 
list.sort(Comparator.comparing(SalesPrecisionMarketingVo::getDeliverySection).reversed());
 

 对list中值进行处理,并且输出一个新的流

属于中间操作,性能上不太好,还不如for循环,在某些特定调式的时候可以用

list = rList.stream().peek(e->e.setSequenceR(arrR[0] ++)).collect(Collectors.toList());

把list转为map

Function.identity()值的是整个对象的值当作vaule
Map<Long, RepairConnectorOrder> map = repairConnectorOrders.stream().collect(Collectors.toMap(RepairConnectorOrder::getId, Function.identity()));

把list对象以某个字段进行分组

Map<String, List<TestDto>> map = result.stream().collect(Collectors.groupingBy(TestDto::getTimePoint));

把list对象某个值取出来变为list<String>

List<String> Ids = newList.stream().map(UserInfoDto::getId).collect(Collectors.toList());

取两个list对象的交集,去重,差集

//交集
List<Person> newList = restList.stream().filter(item -> personList.stream().map(Person::getId).collect(Collectors.toList()).contains(item.getId())).collect(Collectors.toList());
或者
List<Person> listC = listA.stream().filter(item -> listB.contains(item)).collect(Collectors.toList());
//去重
List<Person> listC = listA.stream().distinct().collect(Collectors.toList());
//差集
List<Person> listC = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());

写了一些常用的,后续如果用到一些其他的继续更新

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随风奔跑的十八岁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值