Remove All Elements from Java TreeSet Example

This Java Example shows how to remove all elements contained in Java TreeSet or clear TreeSet object using clear() method.

Remove All Elements from Java TreeSet Example

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
        numbers.clear();
        System.out.println("After clear() method -> " + numbers);
    }
}

Output

numbers TreeSet : [10, 15, 20, 25, 30, 42, 49, 50]
After clear() method -> []

Comments