1. Introduction
TreeSet in Java is part of the Java Collections Framework and is a NavigableSet implementation based on a TreeMap. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order. In this blog, we will perform some basic operations on a TreeSet such as adding elements, removing elements, and iterating over elements.
2. Program Steps
1. Create a TreeSet instance.
2. Add elements to the TreeSet using the add method.
3. Remove an element from the TreeSet using the remove method.
4. Check if an element exists in the TreeSet using the contains method.
5. Iterate over the elements of the TreeSet using a for-each loop and print each element.
3. Code Program
import java.util.TreeSet;
public class TreeSetBasicOperations {
public static void main(String[] args) {
// Step 1: Create a TreeSet instance
TreeSet<String> treeSet = new TreeSet<>();
// Step 2: Add elements to the TreeSet
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Cherry");
System.out.println("TreeSet after adding elements: " + treeSet);
// Step 3: Remove an element from the TreeSet
treeSet.remove("Banana");
System.out.println("TreeSet after removing 'Banana': " + treeSet);
// Step 4: Check if an element exists in the TreeSet
if(treeSet.contains("Cherry")) {
System.out.println("TreeSet contains 'Cherry'");
}
// Step 5: Iterate over the elements of the TreeSet and print each element
System.out.println("Iterating over elements of TreeSet:");
for(String element : treeSet) {
System.out.println(element);
}
}
}
Output:
TreeSet after adding elements: [Apple, Banana, Cherry] TreeSet after removing 'Banana': [Apple, Cherry] TreeSet contains 'Cherry' Iterating over elements of TreeSet: Apple Cherry
4. Step By Step Explanation
Step 1: We create an instance of TreeSet that will store strings.
Step 2: We add three string elements "Apple", "Banana", and "Cherry" to the TreeSet. The TreeSet is printed, showing that elements are stored in ascending order.
Step 3: We remove the element "Banana" from the TreeSet and print it again to show the remaining elements.
Step 4: We check if "Cherry" exists in the TreeSet using the contains method and print the result.
Step 5: We iterate over the elements of the TreeSet using a for-each loop and print each element, demonstrating that the elements are in ascending order.