I have two maps of String with long , I want to calculate percentage by comparing one map value with another map value.
For eg :
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);
I want to calculate average of test1 and test2 value by comparing map2 value with map1 value.
Desired Result should be
resultmap = [test1 : "16.66%", test2 : "25%"]
Something like this
private static String asPercent(long l1, long l2) {
return String.format("%2.2f%%", ((float) l1 / l2 * 100));
}
and
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);
This assumes that for every key you have in map1 there is an entry in map2.
My code produces 16.67% and you wanted 16.66%; if you really need truncation instead of a more accurate (mathematically) rounding, you will probably need to add some rounding code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With