Java-8 lambda表达式等同于传统的

时间:2017-04-10 11:05:10

标签: 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<DistributedCredit> distributedCreditList = iDistributionPlanService.loadByEntityId(distributionPlan.getId()).getDistributedCredit();
    for (DistributedCredit distributedCredit : distributedCreditList) {
        totalDistributedCredit += distributedCredit.getDistributedAmount();
    }
}

我想将我的代码转换为Stream&amp;在Java 8中收集,返回双值

1 个答案:

答案 0 :(得分:0)

以下应该工作:

double sum = distributionPlanList.stream()
    .flatMap(e -> iDistributionPlanService.loadByEntityId(e.getId()).getDistributedCredit().stream())
    .map(dc -> dc.getDistributedAmount())
    .mapToDouble(Double::doubleValue)
    .sum();