The Java Collections Framework includes the TreeMap class, in which Java offers a sorted collection of key-value pairs. By default, TreeMap uses a custom Comparator or arranges components according to their natural ordering. In this article, we will learn how to apply a custom order for key-value pairs in a TreeMap.
Sorting for Key-Value Pairs in a TreeMap
We must provide a custom Comparator during TreeMap instantiation to create a custom order for key-value pairs in a TreeMap. The items’ storage order will be specified by this comparator.
Program to Implement a Custom Order for Key-Value Pairs in a TreeMap
Assume for the moment that we have a TreeMap with people’s names as values and their ages as keys. The entries should be arranged in decreasing order according to age.
Below is the Program to Implement a Custom Order for Key-Value Pairs in a TreeMap:
// Java program to apply a custom order // For key-value pairs in a TreeMap import java.util.*;
// Driver Class public class CustomOrderTreeMap
{ // Main Method
public static void main(String[] args) {
// Creating a TreeMap with a custom comparator
// For descending order based on keys (ages)
TreeMap<Integer, String> customOrderedMap = new TreeMap<>(Collections.reverseOrder());
// Adding key-value pairs
customOrderedMap.put( 25 , "Rahul" );
customOrderedMap.put( 30 , "Abhi" );
customOrderedMap.put( 22 , "Charan" );
customOrderedMap.put( 35 , "Gopi" );
// Displaying the TreeMap
System.out.println( "Custom Ordered TreeMap: " + customOrderedMap);
}
} |
Custom Ordered TreeMap: {35=Gopi, 30=Abhi, 25=Rahul, 22=Charan}
Explanation of the Program:
- In the above program, we have instantiated a customOrderedMap TreeMap, we provide Collections.reverseOrder() as the Comparator. This guarantees that the items are arranged according to keys (ages) in decreasing order.
- We expand the TreeMap with key-value pairs.
- The TreeMap with its items Sorted according to the unique order specified by the Comparator is Shown in the Output.