【问题标题】:Calculate Percentage by comparing 2 Maps using java 8 stream API?通过使用 java 8 流 API 比较 2 个地图来计算百分比?
【发布时间】:2017-10-15 18:12:47
【问题描述】:

我有两个长字符串映射,我想通过比较一个映射值与另一个映射值来计算百分比。

例如:

Map<String, Long> map1 = new ConcurrentHashMap<String, Long>();
map1.put("test1", (long) 20);
map1.put("test2", (long) 30);
Map<String, Long> map2 = new ConcurrentHashMap<String, Long>();
map2.put("test1", (long) 120);
map2.put("test2", (long) 120);

我想通过比较 map2 值和 map1 值来计算 test1 和 test2 值的平均值。

期望的结果应该是

resultmap = [test1 : "16.66%", test2 : "25%"]

【问题讨论】:

  • 您能告诉我们您是如何计算这些值的吗? test1 = 20/120 = 0.1667 吗?
  • 是 test1=20/120 * 100 = 16.67% test2=30/120 * 100 = 25%
  • 我不知道“有缺陷”,但我很难考虑如何使用流来做到这一点。程序上并不太难。
  • @Aominè 我想使用 java 8 流 API 来实现。如果您有更简单的方法,请提出建议。
  • 您可能希望研究使用对来清理数据结构。 commons.apache.org/proper/commons-lang/apidocs/org/apache/…

标签: java java-8 java-stream


【解决方案1】:

类似的东西

private static String asPercent(long l1, long l2) {
    return String.format("%2.2f%%", ((float) l1 / l2 * 100));
}

和

final Map<String, String> percentMap = map1.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> asPercent(entry.getValue(), map2.get(entry.getKey()))));
System.out.println(percentMap);

这假设您在map1 中拥有的每个键在map2 中都有一个条目。

我的代码产生16.67%,而你想要16.66%;如果您确实需要截断而不是更准确(数学上)的舍入,则可能需要添加一些舍入代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2021-01-10
    相关资源
    最近更新 更多