【问题标题】:Map<String, Integer> getting rounded int percentageMap<String, Integer> 得到四舍五入的 int 百分比
【发布时间】:2018-12-27 15:32:51
【问题描述】:

我有一个Map&lt;String, Integer&gt; 和一个名为 globalValue 的整数。我的目标是用 globalValue 的百分比替换地图中的值,例如; (value1/globalValue)*100 并四舍五入。

我曾尝试直接在地图中进行除法(结果为 0),并尝试将我的整数转换为地图内外的双精度数(均导致类型不匹配)。

public Map<String, Integer> analyse() {
    int globalValue = 0;
    Map<String, Integer> m = new HashMap<String, Integer>();
    for (int i = 0; i < array.length; i++) {
        if (array[i].getTime() != null) {
            globalValue = globalValue + array[i].getValue();
            if (m.containsKey(array[i].getTime())) {
                m.put(array[i].getTime(), m.get(array[i].getTime()) + array[i].getValue());
            } else {
                m.put(array[i].getTime(), array[i].getValue());
            }
        }
    }
    return m;
}

【问题讨论】:

  • 为什么不制作Double 的地图而不是Integer
  • 在您的array 上提供一些详细信息
  • 代码中没有(value1/globalValue)*100除法逻辑,你能解释一下你到底需要什么吗?要么除法逻辑?还是改写上面的代码?
  • 正如 GBlodgett 建议的那样,改用 Double 或尝试转换值 (Integer)?
  • “我尝试直接在地图中进行除法(结果为 0)”很可能是因为您正在执行整数除法。将其中一个操作数设为双精度。但是,您当前的代码没有显示任何逻辑....

标签: java


【解决方案1】:

使用 Stream API 会简单得多。您还需要使用doubleDouble 来避免将所有值四舍五入为0。

public Map<String, Double> analyse() {
    double sum = Stream.of(array).mapToDouble(d -> d.getValue()).sum();
    return Stream.of(array)
            .collect(Collectors.groupingBy(t -> t.getTime(),
                    Collectors.summingDouble(t -> t.getValue() * 100.0 / sum)));
}

为什么int 值会发生这种情况?

Int division: Why is the result of 1/3 == 0?

大多数孩子在小学学习整数除法,但一旦我们学习小数,似乎就忘记了。

返回Integer 百分比而不会造成太多的精度损失。

public Map<String, Integer> analyse() {
    long sum = Stream.of(array).mapToLong(d -> d.getValue()).sum();
    Map<String, Long> map = Stream.of(array)
            .collect(Collectors.groupingBy(t -> t.getTime(),
                    Collectors.summingLong(t -> t.getValue())));
    return map.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                    e -> (int) Math.round(100.0 * e.getValue() / sum)));
}

这可以处理许多小值加起来最多为 1% 的情况。

【讨论】:

  • 好吧,我的返回类型必须是整数。
  • @J.Doe 然后返回一个整数.. 只是不要用整数进行计算
  • @J.Doe 我添加了一个计算整数的解决方案,以减少精度损失。
  • @xtratic 这取决于100 * long 的溢出或100.0 * long 的精度损失是否更有可能。
  • @xtratic 好点,在第一个例子中 sum 为 `double` 但我在第二种情况下放弃了它。
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 2021-02-18
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
相关资源
最近更新 更多