Skip to content
Advertisement

Find the key value with respect to value by using comparing with each item in Map List in Java

I have a problem about finding key value with respect to value by using comparing with each item in Map List in Java.

If multiple key values with the same value, I want to get the highest character value. If all key values are different, I want to get a key with the highest value.

Here is my screenshot shown below.

JavaScript

I have a problem in compare part which I cannot handle with.

How can I fix my issue?

Here is my code snippet shown below.

JavaScript

Advertisement

Answer

Assuming you have a map Map<Character,Integer> and want to return a Character, taking your sample input as an example:

JavaScript

you can use stream.max() which takes a comparator, where you could pass a comparator composed by a value-comparator and key-comparator using Comparator.thenComparing:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement