Java HashMap sorting <String, Integer>. How to sort it?

Possible duplicate:
How to sort the <Key, Value> map by values ​​in Java?

In my project, I took 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 need to sort this list according to the given Integer values

Sorted by HashMap. Must be:

{a = 5, f = 5, c = 4, e = 4, b = 4, d = 2}

How can i do this?

+5
source share
4 answers

A HashMapis an unordered collection. It has no sort order. It TreeMapwill even sort by key, not by value.

, , ArrayList<Map.Entry<String,Integer>>, HashMap , Collections.sort .

+11

, HashMap .

TreeMap, . , :

fooobar.com/questions/31/...

+4
ArrayList<Integer> sortedHashMap=new ArrayList<Integer>();

for("your Object" m : degree.values())
{
      sortedHashMap.add(m);
}

collections.sort(sortedHashMap);

- -!

+1

You can do insertion sort to create a new hash file from the original (takes up x2 memory and is very inefficient). So you need the .get () and .set () methods of the hashmap almost n * n (worst case) when n is the number of elements.

0
source

All Articles