DescendingSet: Reverse Order Views
What You'll Learn
You'll learn how to obtain a reversed view of a NavigableSet that automatically reflects any changes made to the original set.
The Core Idea
The descendingSet() method returns a view of your NavigableSet in reverse order. This isn't a copy—it's a live, bidirectional connection to the original set. Changes made through the descending view affect the original set, and vice versa.
Think of it like looking at a bookshelf through a mirror. The mirror shows books in reversed order, but they're still the same books on the same shelf. If you rearrange books using the mirror's reflection, the actual shelf changes too.
How It Works
When you call descendingSet() on a NavigableSet (like TreeSet), you get back another NavigableSet that iterates through elements in reverse order. Any add, remove, or other modification operation works on both views simultaneously.
NavigableSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
// Get descending view
NavigableSet<Integer> reversed = numbers.descendingSet();
// Original: [10, 20, 30, 40]
// Reversed: [40, 30, 20, 10]
reversed.add(25); // Add through reversed view
// Now both views contain 25
// Original: [10, 20, 25, 30, 40]
// Reversed: [40, 30, 25, 20, 10]
numbers.remove(30); // Remove from original
// 30 disappears from both views
// Original: [10, 20, 25, 40]
// Reversed: [40, 25, 20, 10]
The descending view doesn't create a separate data structure—it simply changes how you navigate the existing one.
Key Takeaway: descendingSet() returns a live, reverse-order view of a NavigableSet where modifications to either the original or the view are immediately visible in both.