wood burning stoves 2.0*
The moose likes Java in General and the fly likes sorting hashmap based on values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "sorting hashmap based on values" Watch "sorting hashmap based on values" New topic

sorting hashmap based on values

santhoshkumar samala
Ranch Hand

Joined: Nov 12, 2003
Posts: 156

I need to sort hashmap based on values and not keys.. one more concern here is the values are duplicate..
the hash map has data like

HashMap hashMap=new HashMap();

hashMap.put("aaa",new Integer("333"));
hashMap.put("bbb",new Integer("111"));
hashMap.put("ccc",new Integer("444"));
hashMap.put("eee",new Integer("222"));
hashMap.put("ggg",new Integer("333"));

after sorting the map shuld have the data like

hashMap.put("bbb",new Integer("111"));
hashMap.put("eee",new Integer("222"));
hashMap.put("aaa",new Integer("333"));
hashMap.put("ggg",new Integer("333"));
hashMap.put("ccc",new Integer("444"));

can you please help me in solving this...

santhosh<br />SCJP,SCWCD
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
come from www.theserverside.com/discussions/thread.tss?thread_id=29569. But the link break I used cached page from google. You can google search to find it.

Map someMap= new HashMap();


List mapKeys = new ArrayList(someMap.keySet());
List mapValues = new ArrayList(someMap.values());


TreeSet sortedSet = new TreeSet(mapValues);

Object[] sortedArray = sortedSet.toArray();

int size = sortedArray.length;

// a) Ascending sort

for (int i=0; i<size; i++)

// System.out.println(sortedArray[i]);

someMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedArray[i]);




// b) Descending sort

for (int i=size; i>0

someMap.put(mapKeys.get(mapValues.indexOf(sortedArray[--i])), sortedArray[i]);


Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
You could also use a SortedSet<Entry.Map<String,Integer>> instad of a Map.

Then create a Comparator<Map.Entry<String,Integer>> and use it in the TreeMap to get your items ordered according to the value and not the key.
subject: sorting hashmap based on values
Similar Threads
Nested Map
How to split a string by the whitespace but ignoring '\n'?
Need help for using Iterator
Spring Batch - Issue in reading & writing the quoted fields
displaying the most highly repeated entry in an ArrayList