Signup/Sign In

Sorting a HashMap in Java

The HashMap class in Java is used to store a collection of key-value pairs. It implements the Map interface. HashMap does not store the key-value pairs in sorted order, and they don't maintain the insertion order of elements.

However, there may be cases when we want to view the data stored in a sorted manner. We can sort a HashMap by keys or by values.

In this tutorial, we will learn how to sort a HashMap.

Sorting HashMap by Using Collections.sort()

The Collections framework provides a convenient sort() method to sort elements. We can copy the keys or the values from the HashMap to the ArrayList and then, we can easily sort them by using the Collections.sort() method.

Sorting by Keys

We can get the keys present in a HashMap by using the keySet() method. We can pass this key-set to the ArrayList constructor. This will initialize the ArrayList with the HashMap keys. Next, we will simply use the sort() method and print the sorted keys and the corresponding values.

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		//Creating an ArrayList with the HashMap keys
		ArrayList<String> sortedList = new ArrayList<>(unsortedMap.keySet());
		Collections.sort(sortedList);//Sorting the ArrayList
		
		System.out.println("\nPrinting the Alphabetically Sorted Keys");
		for(String s : sortedList)
		{
			System.out.println(s + "-->" + unsortedMap.get(s));
		}
	}
}


Printing the Unsorted HashMap
four-->4
one-->1
two-->2
three-->3
five-->5

Printing the Alphabetically Sorted Keys
five-->5
four-->4
one-->1
three-->3
two-->2

Sorting by Values

Again, the approach will be the same. We will first initialize an ArrayList with the HashMap values by using the values() method. Then, we can sort them by using the sort() method. We won't be able to see the corresponding keys for the sorted values. There is no way to fetch keys from a HashMap given a value.

package snippet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		//Creating an ArrayList with HashMap values
		ArrayList<Integer> sortedList = new ArrayList<>(unsortedMap.values());
		Collections.sort(sortedList);//Sorting the ArrayList
		
		System.out.println("\nPrinting the Sorted Values");
		for(Integer i : sortedList)
		{
			System.out.println(i);
		}
	}
}


Printing the Unsorted HashMap
four-->4
one-->1
two-->2
three-->3
five-->5

Printing the Sorted Values
1
2
3
4
5

Sorting HashMap by Using TreeMap

If you frequently want to view your HashMap sorted by keys, then a TreeMap would be a better alternative than a HashMap. A TreeMap automatically stores the key-value pairs in sorted order(sorted by keys). We can copy all the data from our HashMap to a TreeMap, and the data will be sorted. We can either use the putAll() method or pass the HashMap to the TreeMap constructor.

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

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		
		TreeMap<String, Integer> sortedMap = new TreeMap<>(unsortedMap);//Passing HashMap object to TreeMap constructor
		//We can also use sortedMap.putAll(unsortedMap); 
		
		System.out.println("\nPrinting the Sorted TreeMap");
		for(Entry<String, Integer> e : sortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}	
	}
}


Printing the Unsorted HashMap
four-->4
one-->1
two-->2
three-->3
five-->5

Printing the Sorted TreeMap
five-->5
four-->4
one-->1
three-->3
two-->2

Sorting HashMap by Values using TreeSet

A HashMap must contain unique keys, but there is no restriction on the values. It can contain duplicate values. We can sort a HashMap by keys with the help of a TreeSet if we only want to consider duplicate values once. Just like TreeMap, a TreeSet also stores data in sorted order. We need to copy the values from the map to the set, and that's it.

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeSet;

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		//Adding Duplicate Values
		unsortedMap.put("fourteen", 4);
		unsortedMap.put("fifteen", 5);
		unsortedMap.put("twenty", 2);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		//Creating a TreeSet using the HashMap values
		TreeSet<Integer> sortedSet = new TreeSet<>(unsortedMap.values());
		
		System.out.println("\nThe sorted values are: " + sortedSet);
	}
}


Printing the Unsorted HashMap
fifteen-->5
four-->4
one-->1
two-->2
three-->3
five-->5
fourteen-->4
twenty-->2

The sorted values are: [1, 2, 3, 4, 5]

Sorting HashMap using Stream and Lambda Expressions

We can sort a HashMap in a single line of code by using Java Streams and the Lambda expressions. We will use call the sorted() object on the stream of the key-value entries.

Sorting by Keys

We will use the comparingByKey comparator with the sorted() method to sort the map by keys.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		
		
		Stream sortedStream = unsortedMap.entrySet()
										 .stream()
										 .sorted(Map.Entry.<String, Integer>comparingByKey());
		System.out.println("\nPrinting the Sorted Key-Value Pairs");
		sortedStream.forEach(System.out :: println);
		
	}
}


Printing the Unsorted HashMap
four-->4
one-->1
two-->2
three-->3
five-->5

Printing the Sorted Key-Value Pairs
five=5
four=4
one=1
three=3
two=2

Sorting by Values

We will use the comparingByValue comparator to sort the HashMap according to the values.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		
		
		Stream sortedStream = unsortedMap.entrySet()
										 .stream()
										 .sorted(Map.Entry.<String, Integer>comparingByValue());
		System.out.println("\nPrinting the Sorted Key-Value Pairs");
		sortedStream.forEach(System.out :: println);
		
	}
}


Printing the Unsorted HashMap
four-->4
one-->1
two-->2
three-->3
five-->5

Printing the Sorted Key-Value Pairs
one=1
two=2
three=3
four=4
five=5

Using Google's Guava Library

Google's Guava library provides us an ImmutableSortedMap class. We can use the copyOf() method of this class to sort a HashMap. We need to pass the HashMap object to this method as a parameter, and it will return an ImmutableSortedMap object. The returned ImmutableSortedMap contains all the entries of our HashMap sorted by keys. Natural ordering is used for sorting.

import java.util.HashMap;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableSortedMap;

public class HashMapSortDemo
{
	public static void main(String args[])
	{
		HashMap<String, Integer> unsortedMap = new HashMap<>();
		unsortedMap.put("one", 1);
		unsortedMap.put("two", 2);
		unsortedMap.put("three", 3);
		unsortedMap.put("four", 4);
		unsortedMap.put("five", 5);
		
		System.out.println("Printing the Unsorted HashMap");
		for(Entry<String, Integer> e : unsortedMap.entrySet())
		{
			System.out.println(e.getKey() + "-->" + e.getValue());
		}
		
		//Creating an ImmutableSortedMap using the HashMap
		ImmutableSortedMap sortedMap = ImmutableSortedMap.copyOf(unsortedMap);
		
		System.out.println("\nPrinting the Sorted ImmutableSortedMap");
		System.out.println(sortedMap);
	}
}


Printing the Unsorted HashMap
four-->4
one-->1
two-->2
three-->3
five-->5

Printing the Sorted ImmutableSortedMap
{five=5, four=4, one=1, three=3, two=2}

Summary

A HashMap is a convenient Collection to use when we want to store key-value pairs. Internally, it uses the concept of Hash Tables. There is no inbuilt method to sort a HashMap. However, we can view the sorted HashMap entries by using other collections like ArrayLists, and TreeSets. TreeMaps are a good alternative to consider if you want to maintain the map entries in sorted order. We can also store the sorted key-value pairs in a LinkedHashMap. LinkedHashMap maintains the insertion order of elements, and we will need to sort the map just once.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.