开发随手记一些常用的吧。
对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());
写了一些常用的,后续如果用到一些其他的继续更新