1. Introduction
Sorting a Map by value is a common task in Java. Unlike sorting by keys, Java Collections Framework doesn’t provide a direct utility for sorting Map by values. However, using Java 8 and above, we can utilize the Stream API to accomplish this task efficiently.
2. Program Steps
1. Create a HashMap and populate it with some key-value pairs.
2. Print the original Map.
3. Convert the Map to a Stream and sort it by its values.
4. Collect the result into a new Map maintaining the sorted order.
5. Print the sorted Map.
3. Code Program
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SortMapByValue {
public static void main(String[] args) {
// Step 1: Create a HashMap and populate it with some key-value pairs
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("Banana", 3);
unsortedMap.put("Apple", 5);
unsortedMap.put("Cherry", 1);
// Step 2: Print the original Map
System.out.println("Original Map: " + unsortedMap);
// Step 3: Convert the Map to a Stream and sort it by its values
// Step 4: Collect the result into a new Map maintaining the sorted order
Map<String, Integer> sortedMap = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.<String, Integer>comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
// Step 5: Print the sorted Map
System.out.println("Sorted Map by Values: " + sortedMap);
}
}
Output:
Original Map: {Banana=3, Apple=5, Cherry=1} Sorted Map by Values: {Cherry=1, Banana=3, Apple=5}
4. Step By Step Explanation
Step 1: A HashMap named unsortedMap is created and initialized with some key-value pairs.
Step 2: The original Map, which is unsorted by values, is printed to the console.
Step 3: The unsortedMap is converted to a Stream and then sorted by its values using the sorted() method and comparingByValue() comparator.
Step 4: The sorted entries are then collected into a new LinkedHashMap named sortedMap. The LinkedHashMap is used to maintain the order of elements in the Map.
Step 5: Finally, the Map sorted by values, sortedMap, is printed to the console.