是否可以将以下三个步骤合并为一个步骤?
第三步求平均值
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);