Java program to remove all elements of TreeSet collection

Given a TreeSet collection, we have to remove all elements.
Submitted by Nidhi, on June 04, 2022

Problem Solution:

In this program, we will create the TreeSet collection with integer elements. Then we will remove all elements of the TreeSet collection using the clear() method.

Program/Source Code:

The source code to remove all elements of the TreeSet collection is given below. The given program is compiled and executed successfully.

// Java program to remove all elements of 
// TreeSet collection

import java.io.*;
import java.util.*;

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

    tree.add(10);
    tree.add(20);
    tree.add(30);
    tree.add(40);
    tree.add(50);
    tree.add(60);

    System.out.println("TreeSet elements: " + tree);
    tree.clear();
    System.out.println("TreeSet elements: " + tree);
  }
}

Output:

TreeSet elements: [10, 20, 30, 40, 50, 60]
TreeSet elements: []

Explanation:

In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. Here, we created a TreeSet collection tree and add elements using add() method. Then we used the clear() method to remove all elements from TreeSet and printed the result.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.