Java: 使用 Collectors.groupingBy 和 Collectors.reducing 计算并返回 CalculationResultDTO 对象
使用 Collectors.groupingBy 和 Collectors.reducing 计算并返回 CalculationResultDTO 对象
以下代码展示了如何使用 Java Stream API 中的 Collectors.groupingBy 和 Collectors.reducing 方法,对 CalculationResultDTO 对象进行计算并生成新的 CalculationResultDTO 对象列表:
CollectionUtils.emptyIfNull(computeResultExports)
.stream()
.map(item -> levelSubtotalCompute(item, weightGroupDataCount))
// 保证评分项名称和评分项对应值的顺序,需要使用LinkedHashMap保存顺序
.collect(Collectors.groupingBy(CalculationResultDTO::getScoreItemId,
LinkedHashMap::new,
Collectors.reducing(BigDecimal.ZERO,CalculationResultDTO::getCalculationResultValue,BigDecimal::add)))
.entrySet()
.stream()
.map(entry -> new CalculationResultDTO(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
这段代码首先使用 Collectors.groupingBy 方法,根据 CalculationResultDTO 对象的 getScoreItemId 方法返回的评分项 ID 对数据进行分组。同时使用 LinkedHashMap::new 来确保分组结果按照评分项 ID 的顺序排列。接着,使用 Collectors.reducing 方法,将每个分组中的 CalculationResultDTO 对象的 getCalculationResultValue 方法返回的评分值进行累加,并使用 BigDecimal.ZERO 作为初始值。
最后,将分组结果转换为 Entry 对象的流,并使用 map 方法将每个 Entry 对象映射为新的 CalculationResultDTO 对象。最终,使用 Collectors.toList 方法将所有新的 CalculationResultDTO 对象收集到一个列表中。
代码解释:
CollectionUtils.emptyIfNull(computeResultExports): 如果computeResultExports为空,则返回一个空的列表。stream(): 将列表转换为流。map(item -> levelSubtotalCompute(item, weightGroupDataCount)): 对每个元素进行levelSubtotalCompute操作,并返回新的CalculationResultDTO对象。collect(Collectors.groupingBy(CalculationResultDTO::getScoreItemId, LinkedHashMap::new, Collectors.reducing(BigDecimal.ZERO,CalculationResultDTO::getCalculationResultValue,BigDecimal::add))): 使用Collectors.groupingBy和Collectors.reducing对数据进行分组和累加,并使用LinkedHashMap确保分组结果的顺序。entrySet(): 获取分组结果的Entry集合。stream(): 将Entry集合转换为流。map(entry -> new CalculationResultDTO(entry.getKey(), entry.getValue())): 将每个Entry对象映射为新的CalculationResultDTO对象。collect(Collectors.toList()): 将所有新的CalculationResultDTO对象收集到一个列表中。
注意: 代码中的 levelSubtotalCompute 方法是根据实际需求定义的,用于对每个 CalculationResultDTO 对象进行计算。
总结:
这段代码展示了如何使用 Java Stream API 中的 Collectors.groupingBy 和 Collectors.reducing 方法,对 CalculationResultDTO 对象进行计算并生成新的 CalculationResultDTO 对象列表。通过这种方式,可以方便地对数据进行分组、计算和整理,从而实现复杂的业务逻辑。
希望这段代码和解释能够帮助您理解如何使用 Java Stream API 进行数据处理。
原文地址: https://www.cveoy.top/t/topic/qFgs 著作权归作者所有。请勿转载和采集!