The following program demonstrates An Example of Using TreeSet in Java.
In this example, we use the generic collection class TreeSet to store string values. The add() method of the TreeSet adds an element. Whereas, the first() and last() methods return the first and last elements in the TreeSet respectively. In order to display, the elements of the TreeSet, we can use the Iterator object.
import java.util.Iterator;
import java.util.TreeSet;
public class TreesetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<String> ts=new TreeSet<String>();
ts.add("Apple");
ts.add("Mango");
ts.add("Banana");
ts.add("Orange");
ts.add("Pear");
ts.add("Guava");
System.out.println("Elements in TreeSet: ");
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next().toString());
}
System.out.println("First Element of the TreeSet: "+ts.first());
System.out.println("Last Element of the TreeSet: "+ts.last());
}
}
Output