这段代码片段展示了如何将 BigDecimal 值与 IndexedColors 映射到 Map 中。原始代码创建了多个中间变量来保存字符串键值,而优化后的代码直接将 BigDecimal 值和 IndexedColors 映射到 Map 中,避免了不必要的变量创建,提升了代码的简洁性和可读性。

原始代码:

final BigDecimal coverageSinceLaunchMin = getMinValue(coverageSinceLaunch);
final BigDecimal coverageSinceLaunchMax = getMaxValue(coverageSinceLaunch);
final BigDecimal halfYearActiveMin = getMinValue(halfYearActive);
final BigDecimal halfYearActiveMax = getMaxValue(halfYearActive);

final Map<String, IndexedColors> map = new HashMap<>();

String coverageSinceLaunchMinKey = "5_" + coverageSinceLaunchMin + "%";
String coverageSinceLaunchMaxKey = "5_" + coverageSinceLaunchMax + "%";
String halfYearActiveMinKey = "8_" + halfYearActiveMin + "%";
String halfYearActiveMaxKey = "8_" + halfYearActiveMax + "%";

map.put(coverageSinceLaunchMinKey, IndexedColors.RED);
map.put(coverageSinceLaunchMaxKey, IndexedColors.GREEN);
map.put(halfYearActiveMinKey, IndexedColors.RED);
map.put(halfYearActiveMaxKey, IndexedColors.GREEN);

优化后的代码:

final Map<String, IndexedColors> map = new HashMap<>();

map.put("5_" + coverageSinceLaunchMin + "%", IndexedColors.RED);
map.put("5_" + coverageSinceLaunchMax + "%", IndexedColors.GREEN);
map.put("8_" + halfYearActiveMin + "%", IndexedColors.RED);
map.put("8_" + halfYearActiveMax + "%", IndexedColors.GREEN);

优化后的代码直接使用 BigDecimal 值和 IndexedColors 进行映射,避免了创建中间变量,使得代码更加简洁易懂。这种优化方法适用于任何需要将值直接映射到 Map 的场景。

Java 代码优化:简化 BigDecimal 和 IndexedColors 的映射操作

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

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