Remove Element from TreeSet in Java Example

The Java TreeSet class provides below methods to perform the delete operation on TreeSet.
  • TreeSet.remove() - Removes the specified element from this set if it is present.
  • removeIf() - Removes all of the elements of this collection that satisfy the given predicate.
  • TreeSet.pollFirst() - Retrieves and removes the first (lowest) element, or returns null if this set is empty.
  • TreeSet.pollLast() - Retrieves and removes the last (highest) element, or returns null if this set is empty

Remove Element from Treeset in Java Example

This example demonstrates the usage of above TreeSet class methods.
package com.javaguides.collections.treesetexamples;

import java.util.TreeSet;

public class RemoveTreeSetElementsExample {
    public static void main(String[] args) {
        TreeSet < Integer > numbers = new TreeSet < > ();

        numbers.add(10);
        numbers.add(15);
        numbers.add(20);
        numbers.add(25);
        numbers.add(30);
        numbers.add(42);
        numbers.add(49);
        numbers.add(50);

        System.out.println("numbers TreeSet : " + numbers);

        // Remove an element from the TreeSet
        boolean isRemoved = numbers.remove(49);
        if (isRemoved) {
            System.out.println("After Removing 49 : " + numbers);
        }

        // Remove all elements divisible by 3
        numbers.removeIf(number - > number % 3 == 0);
        System.out.println("After removeIf() : " + numbers);


        // Retrieve and remove the first element from the TreeSet
        Integer num = numbers.pollFirst();
        System.out.println("Removed first element " + num + " from the TreeSet : " + numbers);

        // Retrieve and remove the last element from the TreeSet
        num = numbers.pollLast();
        System.out.println("Removed last element " + num + " from the TreeSet : " + numbers);
    }
}

Output

numbers TreeSet : [10, 15, 20, 25, 30, 42, 49, 50]
After Removing 49 : [10, 15, 20, 25, 30, 42, 50]
After removeIf() : [10, 20, 25, 50]
Removed first element 10 from the TreeSet : [20, 25, 50]
Removed last element 50 from the TreeSet : [20, 25]

Reference


Comments