1. Introduction

In Java, TreeSet is a part of the Java Collections Framework and is used to store elements in a sorted order. By default, it sorts the elements in their natural order. However, we can also use a Comparator to define a custom sorting order. In this blog post, we will see how to use a Comparator to sort elements in a TreeSet.

2. Program Steps

1. Define a Comparator to specify the custom sorting logic.

2. Create a TreeSet by passing the Comparator as a parameter to its constructor.

3. Add elements to the TreeSet.

4. Iterate over the TreeSet and display the sorted elements.

3. Code Program

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

public class TreeSetWithComparator {

    public static void main(String[] args) {
        // Step 1: Define a Comparator to specify the custom sorting logic
        Comparator<String> reverseOrderComparator = (s1, s2) -> s2.compareTo(s1);

        // Step 2: Create a TreeSet by passing the Comparator as a parameter to its constructor
        TreeSet<String> treeSet = new TreeSet<>(reverseOrderComparator);

        // Step 3: Add elements to the TreeSet
        treeSet.add("Apple");
        treeSet.add("Banana");
        treeSet.add("Cherry");

        // Step 4: Iterate over the TreeSet and display the sorted elements
        System.out.println("Elements in TreeSet in reverse order:");
        for (String fruit : treeSet) {
            System.out.println(fruit);
        }
    }
}

Output:

Elements in TreeSet in reverse order:
Cherry
Banana
Apple

4. Step By Step Explanation

Step 1: We define a Comparator, reverseOrderComparator, to specify the custom sorting logic. In this case, we want to sort the strings in reverse order, so we compare s2 with s1.

Step 2: We create a TreeSet named treeSet by passing the reverseOrderComparator as a parameter to its constructor. This makes the TreeSet use our custom sorting logic.

Step 3: We add three string elements "Apple", "Banana", and "Cherry" to the TreeSet. These elements will be sorted according to the custom order defined by the Comparator.

Step 4: We iterate over the TreeSet using an enhanced for loop and print the elements. The elements are displayed in reverse order, demonstrating that the TreeSet is using the custom order defined by the Comparator.