Java TreeSet : Collection Class



TreeSet class :

  1. TreeSet has unique elements like HashSet
  2. TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  3. TreeSet uses Tree for storage and as Data Structure
  4. TreeSet stores elements in ascending order
  5. TreeSet is used to store large amount of data in sorted order.

Lets create an TreeSet using following line of code –

Example #1 : Create TreeSet

package com.c4learn.collection;

import java.util.TreeSet;

public class TreeSetExample {
  public static void main(String[] args) {

    TreeSet<String> treeSet = new TreeSet<String>();

    treeSet.add("A");
    treeSet.add("B");
    treeSet.add("K");
    treeSet.add("F");
    treeSet.add("C");
    treeSet.add("H");

    System.out.println("Tree Set : " + treeSet);
  }
}

Output :

Tree Set : [A, B, C, F, H, K]

In the above example, we have created an TreeSet using the following line –

TreeSet<String> treeSet = new TreeSet<String>();