1. Introduction

In Java, a TreeMap is a map implementation that maintains its entries in ascending key order. This is achieved by using the natural ordering of its keys, or by a provided Comparator at map creation time. In this tutorial, we’ll explore how to use a custom Comparator to have the TreeMap maintain its entries in descending order.

2. Program Steps

1. Define a custom Comparator that orders elements in descending order.

2. Create a TreeMap with the custom Comparator.

3. Populate the TreeMap.

4. Iterate over and print the entries of the TreeMap.

3. Code Program

import java.util.Comparator;
import java.util.TreeMap;

public class DescendingTreeMap {

    public static void main(String[] args) {

        // Step 1: Define a custom Comparator that orders elements in descending order
        Comparator<Integer> descendingOrder = (i1, i2) -> i2.compareTo(i1);

        // Step 2: Create a TreeMap with the custom Comparator
        TreeMap<Integer, String> treeMap = new TreeMap<>(descendingOrder);

        // Step 3: Populate the TreeMap
        treeMap.put(3, "Three");
        treeMap.put(1, "One");
        treeMap.put(4, "Four");
        treeMap.put(2, "Two");

        // Step 4: Iterate over and print the entries of the TreeMap
        System.out.println("TreeMap in descending order:");
        treeMap.forEach((key, value) -> System.out.println(key + " => " + value));
    }
}

Output:

TreeMap in descending order:
4 => Four
3 => Three
2 => Two
1 => One

4. Step By Step Explanation

Step 1: We define a custom Comparator named descendingOrder. Instead of the default behavior of comparing i1 to i2 (which would give an ascending order), we compare i2 to i1. This effectively reverses the ordering and results in a descending order.

Step 2: When creating our TreeMap, we provide our custom Comparator as an argument to its constructor. This informs the TreeMap that we want it to order its keys based on the rules defined in our Comparator.

Step 3: We populate the TreeMap with some sample data. Due to the custom ordering defined, it will keep its keys in descending order.

Step 4: We iterate over the TreeMap and print its entries. As we can see in the output, the keys are indeed in descending order.