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
x
p/11
a/16 -> Here is the result
s/12
d/10
u/13
b/20
c/20 -> Here is the result
d/1
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
Map.Entry<Character, Integer> maxEntry = null;
for(Map.Entry<Character, Integer> entry : list.entrySet()){
if (maxEntry == null || (entry.getKey()
.compareTo(maxEntry.getKey()) >= 0 && entry.getValue()
.compareTo(maxEntry.getValue()) >= 0)) {
maxEntry = entry;
}
System.out.println(entry.getKey() + "/" + entry.getValue());
}
return maxEntry.getKey();
Advertisement
Answer
Assuming you have a map Map<Character,Integer>
and want to return a Character
, taking your sample input as an example:
JavaScript
Map<Character,Integer> map1 = Map.of('p', 11,
'a', 16,
's', 12,
'd', 10,
'u', 13);
Map<Character,Integer> map2 = Map.of('b',20,
'c',20,
'd', 1);
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
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
.
public static Character getMax(Map<Character,Integer> myMap) {
Comparator<Entry<Character,Integer>> byKey = Entry.comparingByKey();
Comparator<Entry<Character,Integer>> byValue = Entry.comparingByValue();
return myMap.entrySet()
.stream()
.max(byValue.thenComparing(byKey))
.map(Entry::getKey)
.orElse(null);
}