Sort HashMap by keys and values

In the previous post, we have learnt how to iterate over the HashMap. In this post, we will see how to sort HashMap by keys and values.

By default, HashMap does not preserve any order. let’s understand how to sort on the basis of keys and values.

Sort HashMap on the basis of Keys:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class HashMapEx {

	public static void  main(String[] args){
		
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(15, "Mobile");
		hm.put(6, "TV");
		hm.put(10, "Laptop");
		hm.put(2, "Desktop");
		hm.put(1, "Tablet");
		hm.put(23, "Microphone");
		
		System.out.println("Before sorting the HashMap");
		//Set hm.entrySet()  = hm.entrySet();
		Iterator iter = hm.entrySet().iterator();	
		while(iter.hasNext()){
			Map.Entry m = (Map.Entry)iter.next();
			System.out.println(m.getKey()+"----"+m.getValue());
		}
		
		System.out.println("After sorting the HashMap");
		Map<Integer,String> map = new TreeMap<Integer,String>(hm);
		Iterator iter1 = map.entrySet().iterator();
		while(iter1.hasNext()){
			Map.Entry m = (Map.Entry)iter1.next();
			System.out.println(m.getKey()+"----"+m.getValue()); //Sort on the basis of keys
		}
	}
}

Output:

Before sorting the HashMap
1—-Tablet
2—-Desktop
23—-Microphone
6—-TV
10—-Laptop
15—-Mobile
After sorting the HashMap
1—-Tablet
2—-Desktop
6—-TV
10—-Laptop
15—-Mobile
23—-Microphone

Sort HashMap on the basis of Values:

We can sort the HashMap on the basis of values by using comparator.

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class HashMapEx {

	public static void  main(String[] args){
		
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(15, "Mobile");
		hm.put(6, "TV");
		hm.put(10, "Laptop");
		hm.put(2, "Desktop");
		hm.put(1, "Tablet");
		hm.put(23, "Microphone");
		
		System.out.println("Before sorting the HashMap");
		//Set hm.entrySet()  = hm.entrySet();
		Iterator iter = hm.entrySet().iterator();	
		while(iter.hasNext()){
			Map.Entry m = (Map.Entry)iter.next();
			System.out.println(m.getKey()+"----"+m.getValue());
		}
		
		System.out.println("After sorting the HashMap");
		Map<Integer,String> map = sortUsingValues(hm);
		Iterator iter1 = map.entrySet().iterator();
		while(iter1.hasNext()){
			Map.Entry m = (Map.Entry)iter1.next();
			System.out.println(m.getKey()+"----"+m.getValue()); //Sort on the basis of values
		}


	}
	

	private static HashMap sortUsingValues(HashMap map) { 
	       List list = new LinkedList(map.entrySet());
	       // Defined Custom Comparator here
	       Collections.sort(list, new Comparator() {
	            public int compare(Object o1, Object o2) {
	               return ((Comparable) ((Map.Entry) (o1)).getValue())
	                  .compareTo(((Map.Entry) (o2)).getValue());
	            }
	       });
	       
	       // use LinkedLIst to maintain the insertion order
	       HashMap sortedHashMap = new LinkedHashMap();
	       for (Iterator it = list.iterator(); it.hasNext();) {
	              Map.Entry entry = (Map.Entry) it.next();
	              sortedHashMap.put(entry.getKey(), entry.getValue());
	       } 
	       return sortedHashMap;
	 }
}

Output:

Before sorting the HashMap
1—-Tablet
2—-Desktop
23—-Microphone
6—-TV
10—-Laptop
15—-Mobile
After sorting the HashMap
2—-Desktop
10—-Laptop
23—-Microphone
15—-Mobile
6—-TV
1—-Tablet


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...