Search code examples
javatreemaps

Java: Maximum value in TreeMap


If I have a TreeMap:

TreeMap<String, Integer> map = new TreeMap<String, Integer>();

I want to print out the String with the highest value. I have seen other questions about sorting, but I am wondering If there is any smooth way to get the maximum value in the map?


Solution

  • Using Java 8, a one-liner for getting a key with the highest value is:

    String s = map.entrySet()
                  .stream()
                  .max(Map.Entry::comparingByValue)
                  .map(Map.Entry::getKey)
                  .orElse(null);
    

    s will be null if the map is empty.