Reputation: 145
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
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
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
Reputation: 73558
No, for that you'd need to switch your key and value. It's the keys that are sorted.
Upvotes: 1