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,
- What is Map ?
- What is Map.Entry ?
- LinkedHashMap and its properties
- How to iterate Map ?
- Java – How to sort LinkedHashMap by its Keys ?
- Java – How to sort LinkedHashMap by its Values ?
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:
- https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
- https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted–
- https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html#comparingByKey-java.util.Comparator-
- https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html#comparingByValue-java.util.Comparator-
Happy Coding !!
Happy Learning !!