Search code examples
javatreemap

How I can find a key ordered in ascending order in treemap, if there are more than one max values?


I have a TreeMap with entries like

["aftab" = 4, "Manoj" = 5, "Rahul" = 5]

I want to get the key with the max value, but if there are two or more max values I want the key that comes first in the map, Manoj in this case. In My application I used Collections.max(map.getKey()) and it is returning Rahul.


Solution

  • Create a Comparator and pass it to Collections.max().

    Map<String, Integer> map = new TreeMap<>(
                Map.of("Aftab", 4, "Manoj", 5, "Rahul", 5));
    
    Comparator<Entry<String,Integer>> comp = Entry.comparingByValue();
    
    Entry<String,Integer> e = Collections.max(map.entrySet(),comp);
    
    System.out.println(e);
    // or
    System.out.println(e.getKey());