Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
In my project, I have taken a HashMap like this
HashMap degree = new HashMap();
Suppose I have:
degree.put("a",5);
degree.put("b",2);
degree.put("c",4);
degree.put("d",2);
degree.put("e",3);
degree.put("f",5);
Now I have to Sort this list according to given Integer values
Sorted HashMap Should be :
{a=5, f=5, c=4, e=4, b=4, d=2}
How I can do this ?
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
Sorting HashMap by Value Simple Example To sort the String values in the list we use a comparator. This comparator sorts the list of values alphabetically. Once, we have sorted the list, we build the HashMap based on this sorted list. HashMap entries are sorted according to String value.
Sort HashMap by Values using Comparator Interface In Java, sorting HashMap by values is complicated because there is no direct method is available. To sort the HashMap by values, we need to create a Comparator. It compares two elements based on the values.
Map doesn't allow duplicate keys, but it allows duplicate values. HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value.
A HashMap
is an unordered collection. It has no sort order. Even a TreeMap
will sort by key, not value.
If you want to prepare a sorted list by the sort order of the values, you'll have to create an appropriate object, such as an ArrayList<Map.Entry<String,Integer>>
, iterate over your HashMap
and insert all the entries, and then call Collections.sort
with a collation function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With