Java sort Map by values (ascending and descending orders)

Simple quick to use examples to sort Map by values, using Java 8 Stream APIs, in ascending and descending (reverse) orders.

In the center of logic is the method Map.Entry.comparingByValue() which compares Map.Entry in natural order on value.

Sort Map by Values using Stream APIs

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

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.comparingByValue())
	.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, david=2, elle=3, charles=4, brian=5}

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.comparingByValue(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  : {brian=5, charles=4, elle=3, david=2, alex=1}

Complete Example

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

package com.howtodoinjava.spring;

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

public class MapSortingExamples {

	public static void main(String[] args) {
		System.out.println("\nSorting using Java8 streams\n");
		
		sortByValueJava8Stream();
	}

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

		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
		unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue())
				.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.comparingByValue(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 Java8 streams

Unsorted Map 		: {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map   		: {alex=1, david=2, elle=3, charles=4, brian=5}
Reverse Sorted Map  : {brian=5, charles=4, elle=3, david=2, 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.

3 thoughts on “Java sort Map by values (ascending and descending orders)”

  1. Is it possible to sort the below list by values in descending order followed by keys in descending order?

    Unsorted Map : {alex=1, charles=1, david=1, brian=2, elle=1}
    Reply
  2. I don’t think you should mutate an external object inside the stream, like

    x -> reverseSortedMap.put(x.getKey(), x.getValue()) 

    . This goes against the proposal of the lambdas and would break on concurrent access

    Reply

Leave a Comment

HowToDoInJava

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