Java program to check whether a TreeSet is empty or not

Given a TreeSet collection, we have to check whether a it is empty or not.
Submitted by Nidhi, on June 04, 2022

Problem Solution:

In this program, we will create a TreeSet collection with integer elements. Then we will check whether created collections are empty or not using the isEmpty() method.

Program/Source Code:

The source code to check whether a TreeSet is empty or not is given below. The given program is compiled and executed successfully.

// Java program to check whether a TreeSet 
// is empty or not

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

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

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

    if (tree.isEmpty()) {
      System.out.println("TreeSet 'tree' is an empty collection.");
    } else {
      System.out.println("TreeSet 'tree' is not an empty collection.");
    }

    if (empty.isEmpty()) {
      System.out.println("TreeSet 'empty' is an empty collection.");
    } else {
      System.out.println("TreeSet 'empty' is not an empty collection.");
    }
  }
}

Output:

TreeSet 'tree' is not an empty collection.
TreeSet 'empty' is an empty collection.

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 two TreeSet collections tree, empty. Then we used the isEmpty() method to check whether created TreeSets are empty or not and printed the appropriate message.

Java TreeSet Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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