What is TreeSet collection in java (class hierarchy & example)

1. What is TreeSet colletion in java ?

  1. Elements in TreeSet are ordered using natural order or Comparator provided.
    • e.g. TreeSet containing integers will be sorted in natural order
    • e.g TreeSet containing user defined objects will be sorted using comparator supplied.
  2. TreeSet is a NavigableSet implementation based on a TreeMap.
    • TreeSet is red black tree based implementation.
    • TreeSet is Red black tree implementation.
    • TreeSet provides guaranteed log(n) cost for the basic operations (add, remove & contains).
  3. TreeSet contains unique element like HashSet.
    • null elements are not allowed in TreeSet.
  4. TreeSet is not  thread safe like HashSet, LinkedHashSet, EnumSet etc.
  5. Iterator of TreeSet is fail-fast.
    • Iterator will throw ConcurrentModificationException, if TreeSet modified at any time after the iterator is created, in any way except through the iterator’s own remove method.

2. TreeSet collection class hierarchy:

TreeSet collection class hierarchy java example
Fig 1: TreeSet collection class hierarchy

3. Program – TreeSet collection of integers & characters in java (example)

package org.learn.collection.set.tset;

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

public class DemoTreeSet {

 public static void main(String[] args) {
  Set<Integer> natualOrderNumber = new TreeSet<>();
  natualOrderNumber.add(100);
  natualOrderNumber.add(50);
  natualOrderNumber.add(40);
  natualOrderNumber.add(200);
  natualOrderNumber.add(10);
  System.out.println("1. Natual order integers in TreeSet: \n"+ natualOrderNumber);
  
  Set<Character> natualOrderCharacter = new TreeSet<>();
  natualOrderCharacter.add('J');
  natualOrderCharacter.add('A');
  natualOrderCharacter.add('V');
  natualOrderCharacter.add('A');
  System.out.println("2. Natual order characters in TreeSet: \n"+ natualOrderCharacter);
 } 
}

4. Output – TreeSet collection of integers & characters in java (example)

1. Natual order integers in TreeSet: 
[10, 40, 50, 100, 200]
2. Natual order characters in TreeSet: 
[A, J, V]
Scroll to Top