Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of Treeset.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of Treeset.

Objective

Write a Java program to demonstrate automatic sorting using a TreeSet.

Algorithm / Approach

  1. Create a TreeSet.
  2. Add several string values (States) to the set in random alphabetical order.
  3. Print the set to observe that it is automatically sorted.
  4. Use state.remove("Orisa") to delete an element and print the updated set.
Test.java
import java.util.*;
class Test {
 public static void main(String[] a)
 {
  TreeSet state = new TreeSet();
  state.add("Uttar Pradesh");
  state.add("Bihar");
  state.add("Kolkata");
  state.add("Orisa");
  System.out.println(state);
  System.out.println("Size = "+state.size());
  state.remove("Orisa");
  System.out.print("Now List is "+state);
 }
}

Expected Output

[Bihar, Kolkata, Orisa, Uttar Pradesh]
Size = 4
Now List is [Bihar, Kolkata, Uttar Pradesh]

Explanation of the Program

  • A Set is a collection that cannot contain duplicate elements.
  • A TreeSet specifically implements the NavigableSet interface and is backed by a TreeMap (a Red-Black tree data structure).
  • The defining feature of a TreeSet is that it automatically sorts its elements in natural ascending order (alphabetical for Strings, numerical for Numbers) as they are inserted.

Complexity

Time Complexity O(log n) - For adding, removing, or searching elements (Tree properties).
Space Complexity O(n)

Common Mistakes

  • Trying to add custom objects to a TreeSet without implementing the Comparable interface. The TreeSet won't know how to sort them and will throw a ClassCastException.
ADVERTISEMENT