TreeSet stores objects in a sorted manner. TreeSet stores its elements in a tree and they are automatically arranged in a sorted order.

TreeSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.

 import java.util.*;

public class DemoTreeSet {

  public static void main(String[] args) {

    TreeSet t1 = new TreeSet();
    t1.add("ggg");
    t1.add("aaa");
    t1.add("ddd");
    t1.add("bbb");
    t1.add("nnn");
    t1.add("lll");

    System.out.println("Contents of treeset");

    Iterator it1 =t1.iterator();

    while(it1.hasNext()){
      Object o1 = it1.next();
      System.out.println(o1);
    }
  }
}

Output:

Contents of treeset
aaa
bbb
ddd
ggg
lll
nnn