工作中一段时间对数据统计操作比较多,总结了部分常用到的Stream流操作。
1. 过滤并判空
//String fundCode,List<GuaranteeSystemBIDataDetailStatistic> totalSealedStatistics
Optional<GuaranteeSystemBIDataDetailStatistic> totalSealedStatistic = totalSealedStatistics.stream().filter(statistic -> statistic.getFundCode().equals(fundCode)).findFirst();
if(totalSealedStatistic.isPresent()){
onLoanDataDetail.setTotalSealedNum(totalSealedStatistic.get().getTotalSealedNum());
}
2. 求和(Stream复用)
//List<AfterLoanDataDetail> afterLoanDataDetailList
Supplier<Stream<AfterLoanDataDetail>> afterLoanDataDetailStream = () -> afterLoanDataDetailList.stream().filter(afterLoanDataDetail -> !FundCode.ZGC_BK.getCode().equals(afterLoanDataDetail.getFundCode()));
Integer totalCompensatedNumSum = afterLoanDataDetailStream.get().collect(Collectors.summingInt(AfterLoanDataDetail::getTotalCompensatedNum));
BigDecimal compensatedBalance = checkData(afterLoanDataDetailStream.get().map(AfterLoanDataDetail::getCompensatedBalance).reduce(BigDecimal.ZERO,BigDecimal::add));
3. 遍历
//List<AfterLoanDataDetailFormat> afterLoanDataDetailFormats
afterLoanDataDetailFormats.forEach( detailFormat -> {
if(!(ALL_FUND_CODE_CHARGE_GUARANTEE_AMOUNT.contains(detailFormat.getFundCode()))){
detailFormat.setWjGuaranteeAmount("-");
detailFormat.setYzGuaranteeAmount("-");
}
});
4. 排序
List<RegionalRatio> regionalRatioList = new Gson().fromJson(request.getRatioData(),new TypeToken<List<RegionalRatio>>(){}.getType());
List<RegionalRatio> regionalRatios = regionalRatioList.stream().filter(regionalRatio -> !TOTAL.equals(regionalRatio.getRegionCode())).collect(Collectors.toList());
/* ---codes--- */
case 1://正序
regionalRatios = regionalRatios.stream().sorted(Comparator.comparing(RegionalRatio::getOnLoanBalance)).collect(Collectors.toList());
break;
case 2://倒序
regionalRatios = regionalRatios.stream().sorted(Comparator.comparing(RegionalRatio::getOnLoanBalance).reversed()).collect(Collectors.toList());
break;
5. 集合合并
//List<GuaranteeSystemBIDataDetailStatistic> onLoanBalanceList0,onLoanBalanceList
//以ProvinceCode为id,id相同的进行LoanBanlanceAmount求和,即对onLoanBalanceList0进行去重合并
onLoanBalanceList = onLoanBalanceList0.stream().collect(Collectors.toMap(GuaranteeSystemBIDataDetailStatistic::getProvinceCode,a->a,(o1,o2)->{
o1.setLoanBanlanceAmount(o1.getLoanBanlanceAmount().add(o2.getLoanBanlanceAmount()));
return o1;
})).values().stream().collect(Collectors.toList());
6. 去重
List<String> occupationList = allStatisticList.stream().map(statistic -> statistic.getOccupation()).distinct().collect(Collectors.toList());