
What is TreeSet in Java Collection?

Example:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample{
public static void main(String [] args){
TreeSet ts = new TreeSet();
ts.add("B");
ts.add("D");
ts.add("A");
ts.add("E");
ts.add("F");
ts.add("C");
Iterator it = ts.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("Size :" + ts.size());
}
}
Output:-
A B C D E F Size :6
Description:- The above program demonstrates you the concept of TreeSet. Here we have created an object of TreeSet and add elements to the tree Set. Then we have iterated the elements of treeset using Iterator and display the elements.

Example:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample{
public static void main(String [] args){
TreeSet ts = new TreeSet();
ts.add("B");
ts.add("D");
ts.add("A");
ts.add("E");
ts.add("F");
ts.add("C");
Iterator it = ts.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("Size :" + ts.size());
}
}
Output:-
A B C D E F Size :6
Description:- The above program demonstrates you the concept of TreeSet. Here we have created an object of TreeSet and add elements to the tree Set. Then we have iterated the elements of treeset using Iterator and display the elements.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.