Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java HashMap sorting <String,Integer> . How to sort it? [duplicate]

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 ?

like image 827
Hardik Avatar asked Sep 01 '12 16:09

Hardik


People also ask

Can HashMap store duplicate values?

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.

How do you sort HashMap based on values?

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.

Can we use comparator with HashMap in Java?

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.

Does Java map allow duplicates?

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.


1 Answers

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.

like image 110
bmargulies Avatar answered Sep 23 '22 21:09

bmargulies