1. Introduction
TreeSet is a NavigableSet implementation in Java that uses a Red-Black tree structure. It provides an efficient means of storing unique elements in a sorted order. There are several ways to remove elements from a TreeSet. In this blog post, we will look at various methods to remove elements and their implications.
2. Program Steps
1. Import necessary packages.
2. Create and populate a TreeSet with some elements.
3. Use the remove() method to remove specific elements.
4. Use the pollFirst() and pollLast() methods to remove and return the first and last elements respectively.
5. Use the clear() method to remove all elements from the TreeSet.
3. Code Program
import java.util.TreeSet;
public class RemoveFromTreeSet {
public static void main(String[] args) {
// Step 2: Create and populate a TreeSet with some elements
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
System.out.println("Original TreeSet: " + numbers);
// Step 3: Use the remove() method
numbers.remove(30);
System.out.println("After removing 30: " + numbers);
// Step 4: Use the pollFirst() and pollLast() methods
numbers.pollFirst();
System.out.println("After pollFirst(): " + numbers);
numbers.pollLast();
System.out.println("After pollLast(): " + numbers);
// Step 5: Use the clear() method
numbers.clear();
System.out.println("After clear(): " + numbers);
}
}
Output:
Original TreeSet: [10, 20, 30, 40, 50] After removing 30: [10, 20, 40, 50] After pollFirst(): [20, 40, 50] After pollLast(): [20, 40] After clear(): []
4. Step By Step Explanation
Step 1: The necessary packages for using TreeSet are imported.
Step 2: A TreeSet named numbers is initialized and populated with integer values.
Step 3: The remove(Object o) method removes the specified element from the set if it is present.
Step 4:
– pollFirst(): This method retrieves and removes the first (lowest) element, or returns null if the set is empty.
– pollLast(): Similarly, it retrieves and removes the last (highest) element, or returns null if the set is empty.
Step 5: The clear() method is used to remove all the elements from the set, making it empty.
These methods offer a range of possibilities when you want to remove elements from a TreeSet, either selectively or all at once.