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();

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.


Anonymous said…
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()];
List tmpkeyList=Arrays.asList(keys);

for(String key:tmpkeyList){



Thanks & Regards
Su Yan said…
This comment has been removed by the author.
Su Yan said…
What is the values are not unique? In


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

Popular posts from this blog

Get Remote IP Address In Axis SOAP Server

Escape HTML and XML in Java

Read and Write Files in Java