Java 8 – How to sort TreeMap entries in descending order ?

In this article, we will discuss how to sort a TreeMap entries (or key-value pairs) in descending-order by its Key in Java 8 using Stream‘s sorted() method and Comparator

Before proceeding with this sorting examples understand below items,

1. Java 8 – Lambda function

  • First, we will get Map entry set from TreeMap
  • Pass extracted entry-set as constructor-argument while creating LinkedList object
  • Use Collections.sort() method by passing converted LinkedList as 1st argument and below lambda expression for reverse order sorting of keys as 2nd argument
    • (map1, map2) -> map2.getKey().compareTo(map1.getKey())
  • Note :- TreeMap stories entries in ascending-order of keys

SortTreeMapByKeysUsingJava8Lambda.java

package net.bench.resources.treemap.keys.sorting;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class SortTreeMapByKeysUsingJava8Lambda {

	public static void main(String[] args) {

		// 1. create TreeMap object of type <String, Integer>
		Map<String, Integer> countryPopulation = new TreeMap<>(); 


		// 1.1 adding key-value pairs to LinkedHashMap object
		countryPopulation.put("Indian", 382357386);
		countryPopulation.put("Chinese", 409900000);
		countryPopulation.put("America", 332429717);
		countryPopulation.put("Russia", 146748590);
		countryPopulation.put("Brazil", 213728559);
		countryPopulation.put("Mexico", 127792286);
		countryPopulation.put("Pakistan", 220892331);


		// 1.2 print - before sorting - random order
		System.out.println("Original TreeMap in Ascending-order of Keys :- \n");


		// 1.3 print Map entries to console
		countryPopulation.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));


		// 1.4 convert Map EntrySet into LinkedList
		List<Map.Entry<String, Integer>> list = new LinkedList<>(
				countryPopulation.entrySet());



		// 2. Sorting according to reverse alphabetical order of Keys
		System.out.println("\n\nSorted TreeMap in "
				+ "descending-order of Keys :- \n");


		// 2.1 Map keys - Descending order sorting
		Collections.sort(list, 
				(map1, map2) -> map2.getKey().compareTo(map1.getKey())
				);



		// 2.2 iterate and store in newly created LinkedHashMap
		Map<String, Integer> tempMapDesc = new LinkedHashMap<>();
		for (Map.Entry<String, Integer> map : list) {
			tempMapDesc.put(map.getKey(), map.getValue());
		}


		// 2.3 print Map using forEach() method
		tempMapDesc.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));
	}
}

Output:

Original TreeMap in Ascending-order of Keys :- 

Key : America		Value : 332429717
Key : Brazil		Value : 213728559
Key : Chinese		Value : 409900000
Key : Indian		Value : 382357386
Key : Mexico		Value : 127792286
Key : Pakistan		Value : 220892331
Key : Russia		Value : 146748590


Sorted TreeMap in descending-order of Keys :- 

Key : Russia		Value : 146748590
Key : Pakistan		Value : 220892331
Key : Mexico		Value : 127792286
Key : Indian		Value : 382357386
Key : Chinese		Value : 409900000
Key : Brazil		Value : 213728559
Key : America		Value : 332429717

2. Java 8 – Map.Entry.comparingByKey() comparator

  • TreeMap stories entries in ascending-order of keys
  • For descending-order sorting of keys pass Map.Entry.comparingByKey(Comparator.reverseOrder()) comparator as argument to Stream‘s sorted() method

SortTreeUsingMapEntryComparingByKey.java

package net.bench.resources.treemap.keys.sorting;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class SortTreeUsingMapEntryComparingByKey {

	public static void main(String[] args) {

		// 1. create TreeMap object of type <String, Integer>
		Map<String, Integer> countryPopulation = new TreeMap<>(); 


		// 1.1 adding key-value pairs to LinkedHashMap object
		countryPopulation.put("Indian", 382357386);
		countryPopulation.put("Chinese", 409900000);
		countryPopulation.put("America", 332429717);
		countryPopulation.put("Russia", 146748590);
		countryPopulation.put("Brazil", 213728559);
		countryPopulation.put("Mexico", 127792286);
		countryPopulation.put("Pakistan", 220892331);


		// 1.2 print - before sorting - random order
		System.out.println("Original TreeMap in Ascending-order of Keys :- \n");


		// 1.3 print Map entries to console
		countryPopulation.forEach((key, value) -> System.out.println(
				"Key : " + key  + "\t\t"  + "Value : "  + value
				));



		// 2. Sorting according to reverse alphabetical order of Keys
		System.out.println("\n\nSorted TreeMap in "
				+ "descending-order of Keys :- \n");


		// 2.1 Descending-order sorting using Map.Entry.comparingByKey()
		countryPopulation
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
		.forEach(entry -> System.out.println(
				"Key : " + entry.getKey() + "\t\t"  + 
						"Value : " + entry.getValue()
				));
	}
}

Output:

Original TreeMap in Ascending-order of Keys :- 

Key : America		Value : 332429717
Key : Brazil		Value : 213728559
Key : Chinese		Value : 409900000
Key : Indian		Value : 382357386
Key : Mexico		Value : 127792286
Key : Pakistan		Value : 220892331
Key : Russia		Value : 146748590


Sorted TreeMap in descending-order of Keys :- 

Key : Russia		Value : 146748590
Key : Pakistan		Value : 220892331
Key : Mexico		Value : 127792286
Key : Indian		Value : 382357386
Key : Chinese		Value : 409900000
Key : Brazil		Value : 213728559
Key : America		Value : 332429717

Important points to remember about Map :

  • HashMap stores entries (Key-Value pairs) in random-order of Keys
  • LinkedHashMap stores entries (Key-Value pairs) as per insertion-order of Keys
  • TreeMap stores entries (Key-Value pairs) in sorted-order of Keys

References:

Happy Coding !!
Happy Learning !!

Java 8 - Comparator.naturalOrder() and Comparator.reverseOrder()
Java – How to Sort TreeMap by it Keys in descending order ?