我有一个sed -n 's/foo\.bar\.Processor\.message(\([^)]*\).*/\1/p' file.html |
grep -oP ';barid=\K\w+'
和一个名为globalValue的整数。我的目标是将地图中的值替换为globalValue的百分比,例如; (value1 / globalValue)* 100并舍入最终数字。
我尝试直接在地图中进行除法(结果为0),还尝试将整数转换为地图中和地图外部的两倍(均导致类型不匹配)。
Map<String, Integer>
答案 0 :(得分:3)
使用Stream API会更简单。您还需要使用double
或Double
来避免将所有值舍入为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%的情况。