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?
Here is an OO solution (i.e., doesn't use
static
methods):Hereby donated to the public domain.
For sure the solution of Stephen is really great, but for those who can't use Guava:
Here's my solution for sorting by value a map. This solution handle the case where there are twice the same value etc...
The exec: http://www.ideone.com/dq3Lu
The output:
Hope it will help some folks
If you have duplicate keys and only a small set of data (<1000) and your code is not performance critical you can just do the following:
inputUnsortedMap is the input to the code.
The variable sortedOutputMap will contain the data in decending order when iterated over. To change order just change > to a < in the if statement.
Is not the fastest sort but does the job without any additional dependencies.
Instead of using
Collections.sort
as some do I'd suggest usingArrays.sort
. Actually whatCollections.sort
does is something like this:It just calls
toArray
on the list and then usesArrays.sort
. This way all the map entries will be copied three times: once from the map to the temporary list (be it a LinkedList or ArrayList), then to the temporary array and finally to the new map.My solution ommits this one step as it does not create unnecessary LinkedList. Here is the code, generic-friendly and performance-optimal:
Create customized comparator and use it while creating new TreeMap object.
Use the below code in your main func
Output:
From http://www.programmersheaven.com/download/49349/download.aspx