我有两个String的long映射,我想通过将一个映射值与另一个映射值进行比较来计算百分比。
例如:
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%"]
像这样
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%
; 如果您确实需要截断而不是更精确的(数学上)舍入,则可能需要添加一些舍入代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句