优化后的代码如下:

final String getSuggested(final List<SuggestedLevelStatisticsDTO> suggestedLevelStatisticsDTOS) {
    final Map<String, BigDecimal> suggested = suggestedLevelStatisticsDTOS.stream()
            .collect(Collectors.toMap(SuggestedLevelStatisticsDTO::getSuggestedLevel,
                    SuggestedLevelStatisticsDTO::getProportion, BigDecimal::add));

    return MessageFormat.format(SUGGESTED, suggested.getOrDefault(EXCELLENT_SUGGESTED_LEVEL, BigDecimal.ZERO),
            suggested.getOrDefault(BE_COMPETENT_SUGGESTED_LEVEL, BigDecimal.ZERO),
            suggested.getOrDefault(BASIC_COMPETENT_SUGGESTED_LEVEL, BigDecimal.ZERO),
            suggested.getOrDefault(INCOMPETENT_SUGGESTED_LEVEL, BigDecimal.ZERO));
}

优化说明:

  • 移除了CollectionUtils.emptyIfNull方法,因为Collectors.toMap方法可以处理空集合。
  • 使用BigDecimal::add作为合并函数,以处理相同key的情况。
  • 使用Map.getOrDefault方法获取占比值,并设置默认值为BigDecimal.ZERO
Java 代码优化: 使用 Stream 和 Map 计算建议等级占比

原文地址: https://www.cveoy.top/t/topic/fiYL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录