Habbo
Habbo

Reputation: 145

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?

Upvotes: 0

Views: 3217

Answers (3)

Paul Boddington
Paul Boddington

Reputation: 37655

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.

Upvotes: 1

Woot4Moo
Woot4Moo

Reputation: 24336

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<>();

Upvotes: 0

Kayaman
Kayaman

Reputation: 73558

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

Upvotes: 1

Related Questions