TreeSet Example in Java

This class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used.This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample {

 public static void main(String[] args) {
  Set ts = new TreeSet();
  System.out.println("TreeSet Initial Size :" + ts.size());
  ts.add(new Long(14));
  ts.add(new Long(4));
  ts.add(new Long(6));
  ts.add(new Long(1));
  System.out.println("TreeSet Current Size :" + ts.size());
  System.out.print("TreeSet elements are : ");
  System.out.print("TreeSet element Using Iterator:");
  Iterator i = ts.iterator();
  while (i.hasNext()) {
   System.out.print( + ", ");


TreeSet Initial Size:0
TreeSet Current Size:5
TreeSet elements are : [1, 4, 6, 12, 14]
TreeSet element Using Iterator: 1, 4, 6, 12, 14, 


Recent Posts