1. Introduction
In Java, sorting a Map by its keys is straightforward, but sometimes we need to sort the Map by its values or in some custom order. This tutorial will guide you on how to perform a custom sort on a Map in Java.
2. Program Steps
1. Import necessary libraries.
2. Initialize a Map with some key-value pairs.
3. Define a custom Comparator to determine the order of the Map entries.
4. Convert the Map to a List of entries.
5. Sort the List using the custom Comparator.
6. Create a new linked Map from the sorted List to maintain the order.
7. Print the original and the sorted Map.
3. Code Program
// Step 1: Import necessary libraries
import java.util.*;
import java.util.stream.*;
class CustomSortMapExample {
public static void main(String[] args) {
// Step 2: Initialize a Map with some key-value pairs
Map<String, Integer> unsortedMap = Map.of(
"John", 35,
"Alice", 25,
"Bob", 30
);
// Step 3: Define a custom Comparator to determine the order of the Map entries
Comparator<Map.Entry<String, Integer>> valueComparator = Map.Entry.comparingByValue();
// Step 4: Convert the Map to a List of entries
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(unsortedMap.entrySet());
// Step 5: Sort the List using the custom Comparator
entryList.sort(valueComparator);
// Step 6: Create a new linked Map from the sorted List to maintain the order
Map<String, Integer> sortedMap = entryList.stream().collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
// Step 7: Print the original and the sorted Map
System.out.println("Original Map: " + unsortedMap);
System.out.println("Sorted Map by Values: " + sortedMap);
}
}
Output:
Original Map: {John=35, Alice=25, Bob=30} Sorted Map by Values: {Alice=25, Bob=30, John=35}
4. Step By Step Explanation
Step 1: Import the necessary libraries for handling maps, lists, comparators, and streams.
Step 2: Initialize an unsortedMap with some key-value pairs.
Step 3: Define a custom Comparator called valueComparator to determine the order of the Map entries based on their values.
Step 4: Convert the unsortedMap to a List of entries called entryList.
Step 5: Sort the entryList using the valueComparator.
Step 6: Create a new linked Map named sortedMap from the sorted entryList to maintain the order using a collector.
Step 7: Print both the original unsortedMap and the sorted sortedMap to visualize the differences in ordering.