java treeset reverse order code example
Example 1: TreeSet descendingIterator() method in java
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDescendingIteratorMethodExample
{
public static void main(String[] args)
{
try
{
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(50);
ts.add(60);
ts.add(70);
ts.add(80);
System.out.println("TreeSet: " + ts);
Iterator<Integer> iterate = ts.descendingIterator();
System.out.println("Values using descendingIterator() method: ");
while(iterate.hasNext())
{
System.out.println(iterate.next());
}
}
catch(NullPointerException ex)
{
System.out.println("Exception: " + ex);
}
}
}
Example 2: TreeSet descendingSet() method in java
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;
public class TreeSetDescendingSetMethodExample
{
public static void main(String[] args)
{
try
{
TreeSet<String> ts = new TreeSet<String>();
ts.add("Apple");
ts.add("Banana");
ts.add("Cherry");
ts.add("Dragon Fruit");
System.out.println("TreeSet: " + ts);
NavigableSet<String> ns = ts.descendingSet();
Iterator<String> iterate = ns.iterator();
System.out.println("Values using descendingSet() method: ");
while(iterate.hasNext())
{
System.out.println(iterate.next());
}
}
catch(NullPointerException ex)
{
System.out.println("Exception: " + ex);
}
}
}