Java Program to demonstrate the use of Treeset.
Objective
Write a Java program to demonstrate automatic sorting using a TreeSet.
Algorithm / Approach
- Create a
TreeSet. - Add several string values (States) to the set in random alphabetical order.
- Print the set to observe that it is automatically sorted.
- 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
Setis a collection that cannot contain duplicate elements. - A
TreeSetspecifically implements theNavigableSetinterface 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
Comparableinterface. The TreeSet won't know how to sort them and will throw aClassCastException.