TreeSet in Java



TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and ascending order. It contains only unique elements and the access & retrieval is quick.

Following is the list of the constructors supported by the TreeSet class.

Sr.NoConstructor & Description
1TreeSet( )
This constructor constructs an empty tree set that will be sorted in an ascending order according to the natural order of its elements.
2TreeSet(Collection c)
This constructor builds a tree set that contains the elements of the collection c.
3TreeSet(Comparator comp)
This constructor constructs an empty tree set that will be sorted according to the given comparator.
4TreeSet(SortedSet ss)
This constructor builds a TreeSet that contains the elements of the given SortedSet.

Let us now see an example to work with TreeSet class −

Example

import java.util.*;
public class Main {
   public static void main(String args[]) {
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("John");
      ts.add("Kevin");
      ts.add("Amy");
      ts.add("Ryan");
      ts.add("Katie");
      ts.add("Tom");
      System.out.println(ts);
   }
}

Output

[Amy, John, Katie, Kevin, Ryan, Tom]

Let us now see another example wherein we are checking for the existence of an element in the TreeSet −

Example

import java.util.*;
public class Main {
   public static void main(String args[]) {
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("John");
      ts.add("Kevin");
      ts.add("Amy");
      ts.add("Ryan");
      ts.add("Katie");
      ts.add("Tom");
      Iterator<String> i = ts.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      System.out.println("The Set has element 'Jacob'? = " +
      ts.contains("Jacob"));
      System.out.println("The Set has element 'Ryan'? = " +
      ts.contains("Ryan"));
   }
}

Output

Amy
John
Katie
Kevin
Ryan
Tom
The Set has element 'Jacob'? = false
The Set has element 'Ryan'? = true

Advertisements