1. Introduction

In Java, the TreeSet is a part of the Collections Framework that stores its elements in a sorted manner, based on their natural order or by a custom-defined order using a Comparator. In situations where we need a different order than the natural one (for instance, descending order instead of the default ascending), we can utilize a Comparator. In this post, we’ll explore how to create a TreeSet with a custom Comparator that sorts the elements in descending order.

2. Program Steps

1. Import necessary packages.

2. Define a custom Comparator for descending order.

3. Create a TreeSet using the custom Comparator.

4. Populate the TreeSet with elements.

5. Display the elements of the TreeSet to confirm they’re in descending order.

3. Code Program

import java.util.Comparator;
import java.util.TreeSet;

public class DescendingTreeSet {

    public static void main(String[] args) {

        // Step 2: Define a custom Comparator for descending order
        Comparator<Integer> descendingComparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer num1, Integer num2) {
                return num2.compareTo(num1);
            }
        };

        // Step 3: Create a TreeSet using the custom Comparator
        TreeSet<Integer> numbers = new TreeSet<>(descendingComparator);

        // Step 4: Populate the TreeSet with elements
        numbers.add(50);
        numbers.add(20);
        numbers.add(10);
        numbers.add(40);
        numbers.add(30);

        // Step 5: Display the elements of the TreeSet
        System.out.println("Elements of the TreeSet in descending order:");
        for(Integer num : numbers) {
            System.out.println(num);
        }
    }
}

Output:

Elements of the TreeSet in descending order:
50
40
30
20
10

4. Step By Step Explanation

Step 1: We import the necessary packages, i.e., Comparator and TreeSet from java.util.

Step 2: A custom Comparator named descendingComparator is defined. This comparator reverses the default order of comparison between two integers using the compareTo method.

Step 3: A new TreeSet named numbers is created by passing our custom comparator as an argument. This ensures that any element added to the TreeSet will be ordered based on our custom descending order.

Step 4: We populate the TreeSet with some random integers.

Step 5: The elements of the TreeSet are displayed using a for-each loop. As observed in the output, the elements are printed in descending order, confirming the custom ordering defined by our comparator.