Java8流-简化发现总数,发现非零结果,并求平均值到单步中

问题描述 投票:1回答:1

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

  • 第一步计算总价
  • 第二步找到非零价格计数
  • 第三步求平均值

    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;
    

    }

java java-8 java-stream
1个回答
2
投票

使用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);
© www.soinside.com 2019 - 2024. All rights reserved.