0

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?

Habbo
  • 155
  • 1
  • 8

3 Answers3

1

No, for that you'd need to switch your key and value. It's the keys that are sorted.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

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.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
0
TreeMap<String, Integer> map = new TreeMap<String, Integer>();

becomes:

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

Assuming you want all highest value strings, else you only want any such string you can use this construct:

Map<Integer, String> map = new TreeMap<>();
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151