Define a Comparator. Mention the methods provided by the Comparator interface. Illustrate its use with a program that demonstrates sorting elements in a TreeSet in reverse order.

Define a Comparator. Mention the methods provided by the Comparator interface. Illustrate its use with a program that demonstrates sorting elements in a TreeSet in reverse order.

Answer:-

Comparator Interface in Java

A Comparator is an interface used to define custom ordering of objects. It is mainly used when you want to sort objects in a way different from their natural order.


Methods of Comparator Interface

MethodDescription
compare(T o1, T o2)Compares two objects and returns: -1 if o1 < o2, 0 if equal, 1 if o1 > o2
equals(Object obj)Checks if two comparators are equal
reversed()Returns a comparator with reversed order (Java 8+)
thenComparing(...)Chains another comparator for secondary sorting (Java 8+)

Program: Sorting Elements in TreeSet in Reverse Order Using Comparator

import java.util.*;

public class ReverseOrderTreeSet {
    public static void main(String[] args) {
        // Custom comparator for reverse order
        Comparator<Integer> reverseComparator = (a, b) -> b - a;

        // TreeSet with custom comparator
        TreeSet<Integer> set = new TreeSet<>(reverseComparator);

        // Adding elements
        set.add(10);
        set.add(5);
        set.add(20);
        set.add(15);

        // Output in reverse order
        System.out.println("TreeSet in reverse order: " + set);
    }
}

Output

TreeSet in reverse order: [20, 15, 10, 5]

Leave a Reply

Your email address will not be published. Required fields are marked *