Java 8 – How to sort LinkedHashMap entries by its Key ?

In this article, we will discuss how to sort a LinkedHashMap entries (or key-value pairs) 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

  • In this approach, first we will get Map entry set from LinkedHashMap
  • Pass entry-set as constructor-argument while creating LinkedList object and use Collections.sort() method by passing converted LinkedList as 1st argument and below lambda expression for natural order sorting as 2nd argument
    • (map1, map2) -> map1.getKey().compareTo(map2.getKey())
  • For reverse order sorting, just twist the comparison logic in the lambda expression as shown below,
    • (map1, map2) -> map2.getKey().compareTo(map1.getKey())

SortLinkedHashMapByKeysUsingJava8Lambda.java

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

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

public class SortLinkedHashMapByKeysUsingJava8Lambda {

	public static void main(String[] args) {

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


		// 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("Before Sorting - Insertion-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 List
		List<Map.Entry<String, Integer>> list = new LinkedList<>(
				countryPopulation.entrySet());



		// 2. Sorting according to alphabetical order of Keys
		System.out.println("\n\nSorting according to "
				+ "alphabetical order of Keys :- \n");


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



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


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



		// 3. Sorting according to reverse alphabetical order of Keys
		System.out.println("\n\nSorting according to "
				+ "reverse alphabetical order of Keys :- \n");


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



		// 3.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());
		}


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

Output:

Before Sorting - Insertion-order of Keys :- 

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


Sorting according to alphabetical 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


Sorting according to reverse alphabetical 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

  • In this approach, we are going to use Stream‘s sorted() method for sorting Map Keys by passing comparator as argument to sorted() method
  • For alphabetical order of keys pass Map.Entry.comparingByKey() comparator
  • For reverse alphabetical order of keys pass Map.Entry.comparingByKey(Comparator.reverseOrder()) comparator

SortLinkedHashUsingMapEntryComparingByKey.java

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

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

public class SortLinkedHashUsingMapEntryComparingByKey {

	public static void main(String[] args) {

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


		// 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("Before Sorting - Insertion-order :- \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 alphabetical order of Keys
		System.out.println("\n\nSorting according to "
				+ "alphabetical order of Keys :- \n");


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



		// 3. Sorting according to reverse alphabetical order of Keys
		System.out.println("\n\nSorting according to "
				+ "reverse alphabetical order of Keys :- \n");


		// 3.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:

Before Sorting - Insertion-order :- 

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


Sorting according to alphabetical 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


Sorting according to reverse alphabetical 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 - How to sort LinkedHashMap entries by its Value ?
Java 8 – How to Sort a Map entries by its Value – 6 ways