how to use descending iterator over a TreeSet using the collection in java
Previous | Home | Next |
In this example we shall see how to use descending iterator over a TreeSet to sort the elements of a TreeSet in a descending order.
For creating a TreeSet we have to import the java.util package in which we have the class java.util.TreeSet which contains the definition and various that can be performed on a TreeSet. In this example we have created a class named CollectionExample in which we have created a TreeSet and added some elements to it.
In this example we have used the descendingIteratro() on the TreeSet object to iterate down the TreeSet elements in adescending manner. i.e to sort the elements of the TreeSet in the descending order. The descendingIterator() is contained in the Iterator interface.
In the following example we have created a TreeSet and added some elements to it. Then we have invoked the descendingIterator() method on the TreeSet object ts. This will iterate and sort the elements of the TreeSet in a descending order. The following statement in the example invokes the descendingIterator on the TreeSet object,itr=ts.descendingIterator();
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args) throws ClassCastException, NullPointerException, ArrayStoreException
{
// TODO Auto-generated method stub
try
{
TreeSet<Integer> ts=new TreeSet<Integer>(); // creating a TreeSet object ts
ts.add(new Integer(2)); // adding object to the TreeSet
ts.add(4);
ts.add(7);
ts.add(8);
ts.add(1);
ts.add(9);
System.out.println("The objects of the tree set using simple Iterator, are as follows: ");
Iterator<Integer> itr=ts.iterator(); // Invoking the iterator() on the tree set of Integer genre
while(itr.hasNext())
{
System.out.println(itr.next()); // displaying the content of the TreeSet using simple iterator
}
/* code given below will give the content of the TreeSet in descending order */
System.out.println("The objects of the tree set using descendingIterator, are as follows: ");
itr=ts.descendingIterator(); // invoking a descending Iterator to the TreeSet
while(itr.hasNext())
{
System.out.println(itr.next()); // displaying the contents of the TreeSet using the descending iterator
}
/* The above code will give the contents of TreeSet in descending order */
}
catch(ClassCastException e)
{
System.out.println(e.getMessage());
}
catch(NullPointerException e)
{
System.out.println(e.getLocalizedMessage());
}
catch(ArrayStoreException e)
{
System.out.println(e.getMessage());
}
}
}
Output of the above example is as follows:
The objects of the tree set using simple Iterator, are as follows:
1
2
4
7
8
9
The objects of the tree set using descendingIterator, are as follows:
9
8
7
4
2
1
Previous | Home | Next |