I am relatively new to Java, and often find that I need to sort a Map<Key, Value>
on the values.
Since the values are not unique, I find myself converting the keySet
into an array
, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key.
Is there an easier way?
Depending on the context, using
java.util.LinkedHashMap<T>
which rememebers the order in which items are placed into the map. Otherwise, if you need to sort values based on their natural ordering, I would recommend maintaining a separate List which can be sorted viaCollections.sort()
.Afaik the most cleaner way is utilizing collections to sort map on value:
Here's a generic-friendly version:
Best Approach
Output
Major problem. If you use the first answer (Google takes you here), change the comparator to add an equal clause, otherwise you cannot get values from the sorted_map by keys:
There are a lot of answers for this question already, but none provided me what I was looking for, a map implementation that returns keys and entries sorted by the associated value, and maintains this property as keys and values are modified in the map. Two other questions ask for this specifically.
I cooked up a generic friendly example that solves this use case. This implementation does not honor all of the contracts of the Map interface, such as reflecting value changes and removals in the sets return from keySet() and entrySet() in the original object. I felt such a solution would be too large to include in a Stack Overflow answer. If I manage to create a more complete implementation, perhaps I will post it to Github and then to it link in an updated version of this answer.