1. Introduction
In Java, the TreeSet class provides a mechanism to store elements in a sorted order. By default, it sorts the elements in their natural ordering. However, there are situations where we may want to sort elements in reverse order. Thankfully, Java provides the Collections.reverseOrder() method, which returns a comparator that imposes the reverse of the natural ordering on a collection of objects. In this post, we’ll demonstrate how to use this method to sort the elements of a TreeSet in reverse order.
2. Program Steps
1. Create a TreeSet with Collections.reverseOrder() as its comparator.
2. Add elements to the TreeSet.
3. Display the elements of the TreeSet to observe them in reverse order.
3. Code Program
import java.util.Collections;
import java.util.TreeSet;
public class TreeSetReverseOrder {
public static void main(String[] args) {
// Step 1: Create a TreeSet with Collections.reverseOrder() as its comparator
TreeSet<String> treeSet = new TreeSet<>(Collections.reverseOrder());
// Step 2: Add elements to the TreeSet
treeSet.add("Orange");
treeSet.add("Apple");
treeSet.add("Banana");
// Step 3: Display the elements of the TreeSet
System.out.println("Elements in TreeSet in reverse order:");
for (String fruit : treeSet) {
System.out.println(fruit);
}
}
}
Output:
Elements in TreeSet in reverse order: Orange Banana Apple
4. Step By Step Explanation
Step 1: We create a TreeSet and specify Collections.reverseOrder() as its comparator. This will ensure that the TreeSet sorts its elements in reverse order.
Step 2: We add the elements "Orange", "Apple", and "Banana" to the TreeSet.
Step 3: When we iterate over the TreeSet and print its elements, we see them in reverse order compared to their natural ordering. Hence, "Orange" appears before "Banana", and "Banana" appears before "Apple". This illustrates how we can use the Collections.reverseOrder() method to reverse the sorting order of a TreeSet.