Java sort Map by key (ascending and descending orders)

Simple quick to use examples to sort a Map by key, using TreeMap and Stream APIs, in ascending and descending (reverse) orders.

Sort Map by Key using TreeMap

In ascending order

By default, all key-value pairs in TreeMap are sorted in their natural order. So all you need to do is add all unsorted key-value pairs in TreeMap.

Map<String, Integer> unSortedMap = getUnSortedMap();
		
System.out.println("Unsorted Map : " + unSortedMap);

Map<String, Integer> sortedMap = new TreeMap<String, Integer>(unSortedMap);

System.out.println("Sorted Map   : " + sortedMap);

Output:

Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map   : {alex=1, brian=5, charles=4, david=2, elle=3}

In descending order

To reverse sort map entries, pass Collections.reverseOrder() in TreeMap constructor.

Map<String, Integer> unSortedMap = getUnSortedMap();
		
System.out.println("Unsorted Map : " + unSortedMap);

Map<String, Integer> reverseSortedMap = new TreeMap<String, Integer>(Collections.reverseOrder());

reverseSortedMap.putAll(unSortedMap);
		
System.out.println("Reverse Sorted Map   : " + reverseSortedMap);

Output:

Unsorted Map 		: {alex=1, charles=4, david=2, brian=5, elle=3}
Reverse Sorted Map  : {elle=3, david=2, charles=4, brian=5, alex=1}

Sort Map by Key using Stream APIs

In java 8, Map.Entry class has static method comparingByKey() to help you in sorting by keys. This method returns a Comparator that compares Map.Entry in natural order on key.

Alternatively, you can pass a custom Comparator to use in sorting. This can be used to sort the map in reverse order.

In ascending order

Map<String, Integer> unSortedMap = getUnSortedMap();
		
System.out.println("Unsorted Map : " + unSortedMap);

//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();

unSortedMap.entrySet()
	.stream()
	.sorted(Map.Entry.comparingByKey())
	.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

System.out.println("Sorted Map   : " + sortedMap);

Output:

Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map   : {alex=1, brian=5, charles=4, david=2, elle=3}

In descending order

Map<String, Integer> unSortedMap = getUnSortedMap();
		
System.out.println("Unsorted Map : " + unSortedMap);

//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();

//Use Comparator.reverseOrder() for reverse ordering
unSortedMap.entrySet()
	.stream()
	.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 
	.forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));

System.out.println("Reverse Sorted Map   : " + reverseSortedMap);

Output:

Unsorted Map 		: {alex=1, charles=4, david=2, brian=5, elle=3}
Reverse Sorted Map  : {elle=3, david=2, charles=4, brian=5, alex=1}

Complete Example

The complete code used in this example, for your reference.

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class MapSortingExamples {

	public static void main(String[] args) {
		
		System.out.println("Sorting using TreeMap\n");
		
		sortByKeyUsingTreeMap();

		System.out.println("\nSorting using Java8 streams\n");
		
		sortByKeyJava8Stream();
	}

	private static void sortByKeyUsingTreeMap() 
	{
		Map<String, Integer> unSortedMap = getUnSortedMap();
		
		System.out.println("Unsorted Map : " + unSortedMap);

		Map<String, Integer> sortedMap = new TreeMap<String, Integer>(unSortedMap);
		
		System.out.println("Sorted Map   : " + sortedMap);
		
		Map<String, Integer> reverseSortedMap = new TreeMap<String, Integer>(Collections.reverseOrder());
		reverseSortedMap.putAll(unSortedMap);
		
		System.out.println("Reverse Sorted Map   : " + reverseSortedMap);
	}

	private static void sortByKeyJava8Stream() 
	{
		Map<String, Integer> unSortedMap = getUnSortedMap();
		
		System.out.println("Unsorted Map : " + unSortedMap);

		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
		unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
				.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
		
		System.out.println("Sorted Map   : " + sortedMap);
		
		LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
		unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
				.forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
		
		System.out.println("Reverse Sorted Map   : " + reverseSortedMap);
	}

	private static Map<String, Integer> getUnSortedMap() 
	{
		Map<String, Integer> unsortMap = new HashMap<>();
		unsortMap.put("alex", 1);
		unsortMap.put("david", 2);
		unsortMap.put("elle", 3);
		unsortMap.put("charles", 4);
		unsortMap.put("brian", 5);
		return unsortMap;
	}
}

Output:

Sorting using TreeMap

Unsorted Map 		: {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map   		: {alex=1, brian=5, charles=4, david=2, elle=3}
Reverse Sorted Map  : {elle=3, david=2, charles=4, brian=5, alex=1}

Sorting using Java8 streams

Unsorted Map 		: {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map   		: {alex=1, brian=5, charles=4, david=2, elle=3}
Reverse Sorted Map  : {elle=3, david=2, charles=4, brian=5, alex=1}

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java sort Map by key (ascending and descending orders)”

  1. Hello Lokesh,

    Thanks for this article.I have a question.
    After sorting, if i want to print the largest value and corresponding key only? How do I do it?
    Sample Output:{alex=1, brian=5, charles=4, david=2, elle=3}
    If I want to print brian=5 alone which has the largest value.

    Regards,
    Ashwin

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.