Java-8 lambda表达式等效于传统的for
我在Java 7中有一个Java-8 lambda表达式等效于传统的for,java,for-loop,lambda,java-8,java-stream,Java,For Loop,Lambda,Java 8,Java Stream,我在Java 7中有一个for语句,它工作正常: Double totalDistributedCredit = 0D; Set<DistributionPlan> distributionPlanList = loadByEntityId(creditResourceId).getDistributionPlan(); for (DistributionPlan distributionPlan : distributionPlanList) { Set<Distri
for
语句,它工作正常:
Double totalDistributedCredit = 0D;
Set<DistributionPlan> distributionPlanList = loadByEntityId(creditResourceId).getDistributionPlan();
for (DistributionPlan distributionPlan : distributionPlanList) {
Set<DistributedCredit> distributedCreditList = iDistributionPlanService.loadByEntityId(distributionPlan.getId()).getDistributedCredit();
for (DistributedCredit distributedCredit : distributedCreditList) {
totalDistributedCredit += distributedCredit.getDistributedAmount();
}
}
Double totalDistributedCredit=0D;
设置distributionPlanList=loadByEntityId(creditResourceId).getDistributionPlan();
for(DistributionPlan DistributionPlan:distributionPlanList){
设置distributedCreditList=iDistributionPlanService.loadByEntityId(distributionPlan.getId()).getDistributedCredit();
for(DistributedCredit DistributedCredit:distributedCreditList){
totalDistributedCredit+=distributedCredit.getDistributedAmount();
}
}
我想在Java8中将代码转换为Stream&collect,并返回一个双精度值 以下方法应该有效:
double sum = distributionPlanList.stream()
.flatMap(e -> iDistributionPlanService.loadByEntityId(e.getId()).getDistributedCredit().stream())
.map(dc -> dc.getDistributedAmount())
.mapToDouble(Double::doubleValue)
.sum();
到目前为止你试过什么?所以这不是翻译服务。非常感谢你的评论。但是我尝试了,但没有收到答案..flatMap(e->iDistributionPlanService.loadByEntityId(e.getId()).getDistributedCredit())错误:类型不匹配:无法从集合转换为流更新答案,请立即尝试?非常感谢您亲爱的朋友,完全正确。如果答案对您有帮助,您可以将其标记为正确。@DarshanMehta
map
和mapToDouble
可以合并到mapToDouble(DistributedCredit::getDistributedAmount)
。