How to Sort HashMap by Key and Value

How to Sort HashMap by Key and Value thumbnail
55K
By Dhiraj 19 October, 2016

HashMap is a class in Java that implements Map interface and holds values based on an unique key.As we know HashMap is an unsorted and unordered Map. Hence, requirements come where we need to sort the HashMap either by its key or values.In this post, we will take a look into how to sort a HashMap by key as well as by value.

Sort HashMap by Key

As we know there is an implementation of NavigableMap interface, known as TreeMap which also holds a key value pair but maintains the key sorted(natural order) in ascending order by default.Hence, to sort a HashMap by it's key it is only required to convert existing HashMap into a TreeMap.Apart from this, we can also define our custom sort order by implementing Comparable or Comparator Interface to sort a TreeMap.

First, let us take a look into how to sort a HashMap by it's key in natural order.

Map<String, String> unsortedMap = new HashMap<Integer,String>();

//Convert HashMap to TreeMap.It will be sorted in natural order.
Map<String,String> treeMap = new TreeMap<String,String>(unsortedMap);

Above code snippet will sort the Map by key in ascending order and it is a natural sorting.Now to sort it in descending order or to sort the map with custom object keys, we need to implement Comparator as below:

Map<Integer,String> unsortedMap = new Hashmap<Integer,String>();
Map<Integer,String> treeMap = new TreeMap<Integer,String>(
	new Comparator<Integer>() {
		@Override
		public int compare(Integer o1, Integer o2) {
			return o2.compareTo(o1);//sort in descending order
		}
		});
		
 Other Interesting Posts
Hello World Java Program Breakup
Serialization and Deserialization in Java with Example
Convert HashMap to List in Java
Why wait(),notify(),notifyAll() defined in object class in Java
How to use Comparable and Comparator in Java with Example

Sort HashMap by Values

Sorting a Hashmap by values is little tricky as TreeMap is unable to sort the Map by it's values.To sort a HashMap by it's values, we need to convert the existing Map into a List and then sort this list by using Comparator interface and then again put this sorted list back to a Map.

Map<String, Integer> unsortedMap = new HashMap<String, Integer>();

		//convert map to a List
		List<Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortedMap.entrySet());

		//sorting the list with a comparator
		Collections.sort(list, new Comparator<Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				return (o1.getValue()).compareTo(o2.getValue());
			}
		});

		//convert sortedMap back to Map
		Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for (Entry<String, Integer> entry : list) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}
	}

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Core Java