Thursday, May 1, 2008

Sort a HashMap based on Keys or Values

Sort based on keys is simple , just dump the map into TreeMap (TreeMap is sorted by nature)

Map myMap = new HashMap();
// put keys and values........
Map sortedMap = new TreeMap(myMap);

If you want to sort your HashMap based on values :

HashMap map1 = new HashMap();
map1.put("cat",5);
map1.put("cow",4);
map1.put("dog",3);
map1.put("horse",2);


List mpKeys = new ArrayList(map1.keySet());
List mpValues = new ArrayList(map1.values());

HashMap map = new LinkedHashMap();
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// descending

for (int i=size-1; i>=0; i--)
System.out.println(mpKeys.get(mpValues.indexOf(sortedArray[i]))+" "+sortedArray[i]);

Any discussions will be appreciated.


6 comments:

Anonymous said...

Thanks.
Correction: Line 13 should read
TreeSet sortedSet = new TreeSet(mpValues);
instead of
TreeSet sortedSet = new TreeSet(mapValues);

pavan said...

Another way:
__________________________________________
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
*
* @author pavanj
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {


HashMap callList = new HashMap();
callList.put("java", "pavan");
callList.put("makes", "srinivas");
callList.put("life", "sample");
callList.put("easy", "java");


Set set=callList.keySet();
String[] keys=new String[set.size()];
set.toArray(keys);
List tmpkeyList=Arrays.asList(keys);

Collections.sort(tmpkeyList);
for(String key:tmpkeyList){
System.out.println(key+":"+callList.get(key));
}

}

}

_________________________________
Thanks & Regards
-----------------
Pavan

Su Yan said...
This comment has been removed by the author.
Su Yan said...

What is the values are not unique? In

(mpKeys.get(mpValues.indexOf(sortedArray[i]))

you will only return the first key with that value.

mahesh muley said...

Hello i got a easy solution

Make use of TreeMap instaed of HashMap it is sorted by default.

Or you can use

new TreeMap(hashMap);

Santy Java said...

code looks code but it needs to be udpated to use Generics. Here is another way of sorting HashMap in Java by keys and values which uses generics