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?
Java 8 offers a new answer: convert the entries into a stream, and use the comparator combinators from Map.Entry:
This will let you consume the entries sorted in ascending order of value. If you want descending value, simply reverse the comparator:
If the values are not comparable, you can pass an explicit comparator:
You can then proceed to use other stream operations to consume the data. For example, if you want the top 10 in a new map:
Or print to
System.out
:You can try Guava's multimaps:
As a result you get a map from original values to collections of keys that correspond to them. This approach can be used even if there are multiple keys for the same value.
Important note:
This code can break in multiple ways. If you intend to use the code provided, be sure to read the comments as well to be aware of the implications. For example, values can no longer be retrieved by their key. (
get
always returnsnull
.)It seems much easier than all of the foregoing. Use a TreeMap as follows:
Output:
Since TreeMap<> does not work for values that can be equal, I used this:
You might want to put list in a LinkedHashMap, but if you're only going to iterate over it right away, that's superfluous...
This is just too complicated. Maps were not supposed to do such job as sorting them by Value. The easiest way is to create your own Class so it fits your requirement.
In example lower you are supposed to add TreeMap a comparator at place where * is. But by java API it gives comparator only keys, not values. All of examples stated here is based on 2 Maps. One Hash and one new Tree. Which is odd.
The example:
So change the map into a set this way:
You will create class
Results
,and the Comparator class:
This way you can easily add more dependencies.
And as the last point I'll add simple iterator:
Use a generic comparator such as :