繁体   English   中英

Java8流 - 将求和、正结果和平均结果的发现合并为一个步骤

[英]Java8 stream - combine the finding of sum, positive result and average result into single step

是否可以将以下 3 个步骤合并为一个步骤?

  • 第一步计算总价
  • 第二步查找非零价格计数
  • 第三步求平均值
private double calculateTotalBCMMatrixCost(SpecificationEntryRequest specificationEntryRequest) {

        // Finds the total BCM matrix cost
        double totalBcmMatrixCost = specificationEntryRequest.getComponentList().stream()
                .map(ComponentDetail::getStartingMaterialId)
                .map(this::calculateBCMMatrixCostForAnalyte)
                .collect(Collectors.summingDouble(Double::doubleValue));

        // Finds the non zero cost count
        long nonZeroPriceCount = specificationEntryRequest.getComponentList().stream()
                .map(ComponentDetail::getStartingMaterialId)
                .map(this::calculateBCMMatrixCostForAnalyte)
                .filter(price -> price > 0).count();

        // returns the average cost
        return totalBcmMatrixCost / nonZeroPriceCount;
    }

使用DoubleSummaryStatistics

DoubleSummaryStatistics stats = specificationEntryRequest.getComponentList().stream()
    .map(ComponentDetail::getStartingMaterialId)
    .mapToDouble(this::calculateBCMMatrixCostForAnalyte)
    .filter(price -> price > 0)
    .summaryStatistics();
double totalBcmMatrixCost = stats.gtSum ();
long nonZeroPriceCount = stats.getCount ();
double average = stats.getAverage ();

或者当然,如果您只需要平均值(这就是您的方法返回的内容),您可以使用:

return specificationEntryRequest.getComponentList().stream()
    .map(ComponentDetail::getStartingMaterialId)
    .mapToDouble(this::calculateBCMMatrixCostForAnalyte)
    .filter(price -> price > 0)
    .average()
    .orElse(0.0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM