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

In this article, we will discuss how to sort a LinkedHashMap entries (key-value pairs) by its Value 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, convert LinkedHashMap entries into List of Map Entry Set
  • Ascending-order values :- Use Collections.sort() method by passing converted List of Map Entry Set as 1st argument and 2nd argument as below lambda expression for ascending-order sorting of values
    • (map1, map2) -> map1.getValue().compareTo(map2.getValue())
  • Descending-order values :- Use Collections.sort() method by passing converted List of Map Entry Set as 1st argument and 2nd argument as below lambda expression for descending-order sorting of values
    • (map1, map2) -> map2.getValue().compareTo(map1.getValue())

SortLinkedHashMapByValuesUsingJava8Lambda.java

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

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

public class SortLinkedHashMapByValuesUsingJava8Lambda {

	public static void main(String[] args) {

		// 1. creating 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
				));


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



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


		// 2.1 Ascending-order sorting of Map Values
		Collections.sort(entrySetList, 
				(map1, map2) -> map1.getValue().compareTo(map2.getValue())
				);



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


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



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


		// 3.1 Descending-order sorting of Map Values
		Collections.sort(entrySetList, 
				(map1, map2) -> map2.getValue().compareTo(map1.getValue())
				);


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


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

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 natural order of Values :- 

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


Sorting according to reverse order of Values :- 

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

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

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

SortLinkedHashUsingMapEntryComparingByValue.java

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

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

public class SortLinkedHashUsingMapEntryComparingByValue {

	public static void main(String[] args) {

		// 1. creating 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 natural order of Map Values
		System.out.println("\n\nSorting according to "
				+ "natural order of Values :- \n");


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



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


		// 3.1 Descending-order sorting using Map.Entry.comparingByValue()
		countryPopulation
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) //reverse
		.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 natural order of Values :- 

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


Sorting according to reverse order of Values :- 

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

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 some sorted-order of Keys

References:

Happy Coding !!
Happy Learning !!

Java – How to Sort TreeMap by it Keys in descending order ?
Java 8 - How to sort LinkedHashMap entries by its Key ?