Spider Man Spider Man - 10 months ago 69
Java Question

How to retrieve the key with a maximum value in a TreeMap in Java?

I have a tree map declared as follows:

TreeMap<Integer, Integer> tree = new TreeMap<Integer, Integer>();


How do I retrieve the key with the maximum value. Is there an O(1) way of achieving this. I know that maximum and minimum keys can be retrieved from a TreeMap in O(1) time as follows:

int maxKey = tree.lastEntry().getKey();
int minKey = tree.firstEntry().getKey();


Thanks for help.

Answer Source

The collection is not sorted by value so the only way is brute force O(n) unless there is another collection with say the reverse map available.

Map<Integer, Integer>map = new TreeMap<>();
int max = map.values().stream().max(Integer::compare).get();