Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Percentage by comparing 2 Maps using java 8 stream API?

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%"]
like image 912
Mohammed Abdullah Avatar asked Aug 10 '26 01:08

Mohammed Abdullah


1 Answers

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.

like image 77
Roman Puchkovskiy Avatar answered Aug 11 '26 15:08

Roman Puchkovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!