The descendingIterator() method of java.util.TreeSet class will return an iterator over the elements in this set in descending order whereas descendingSet() method returns a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa. If either set is modified while an iteration over either set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined.
Signature
public NavigableSet<E> descendingSet()
This method returns a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa.
Example
The following example shows the usage of java.util.TreeSet.descendingSet() method.
import java.util.TreeSet; public class DescendingSetMethodTreeSetExample { public static void main(String args[]) { // create an empty TreeSets TreeSet treeSet = new TreeSet(); TreeSet reverseTreeSet = new TreeSet(); //use add() method to add elements to the TreeSet treeSet.add(1); treeSet.add(12); treeSet.add(3); treeSet.add(17); treeSet.add(5); //Printing the elements of the treeset System.out.println("**Elements of the treeSet**"); for(Integer val : treeSet) { System.out.println(val); } //Lets reverse the elements of the treeSet reverseTreeSet = (TreeSet) treeSet.descendingSet(); //Printing the elements of the reverseTreeSet System.out.println("**Elements of the reverseTreeSet**"); for(Integer val : reverseTreeSet) { System.out.println(val); } } }
Output
**Elements of the treeSet** 1 3 5 12 17 **Elements of the reverseTreeSet** 17 12 5 3 1
Leave a Reply