Java8 Stream對集合的一些應用
阿新 • • 發佈:2021-07-22
工作中一段時間對資料統計操作比較多,總結了部分常用到的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());