stream常用方法记录

  与数据的操作尽量使用批量,这个时候,就出现了很多List,对list的操作,使用stream特别方便,但是有时候,一些方法还是没记住,这里针对常用的方法做一个统计,这篇文档持续更新,将遇到的都记录好。

  方法千万种,这里记录一种。

1.聚合

  可以将list下的每个对象的contractId给过滤出来,然后形成一个list结果。

contractIdList = billTermList.stream().map(ContractBillTermMonitorDetailDTO::getContractId).collect(Collectors.toList());

  

2.分组

  对list中的对象进行分组

Map<Long, List<KasEveryDayBillDataRespDTO>> listMap = contractBillData.stream().collect(Collectors.groupingBy(KasEveryDayBillDataRespDTO::getContractId));

 

3.排序

List<ContractBillTermRecordDTO> sortedHistoryList = historyList.stream().sorted(Comparator.comparing(ContractBillTermRecordDTO::getBillStartTime)).collect(Collectors.toList());

  

4.倒排

List<ContractBillTermRecordDTO> sortedBillTermRecordList = contractBillTermRecordDTOList.stream().sorted(Comparator.comparing(ContractBillTermRecordDTO::getBillStartTime).reversed())
                    .collect(Collectors.toList());

  

5.对Integer字段进行相加

laterMonthBillData = laterList.stream().mapToInt(ContractBillTermRecordDTO::getAmount).sum();

  

6.计算list的个数

int tmp = (int) sortedHistoryList.stream().filter(sortedHistory -> currentBillTermRecordDTO.getBillStartTime().isBefore(sortedHistory.getBillStartTime())).count();

  

7.BigDecimal的相加

contractOverpaidMoneyRecordDTOList.stream().map(ContractOverpaidMoneyRecordDTO::getHasDeductOverpaidAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

  

原文地址:https://www.cnblogs.com/juncaoit/p/12527797.html