Home »
Java »
Java Programs
Java program to check whether an item exists in a TreeSet collection or not
Given a TreeSet collection, we have to check whether an item exists in it or not.
Submitted by Nidhi, on June 05, 2022
Problem statement
In this program, we will create a TreeSet collection with integer elements. Then we will use contains() method to check whether an item exists in a TreeSet collection or not.
Java program to check whether an item exists in a TreeSet collection or not
The source code to check whether an item exists in a TreeSet collection or not is given below. The given program is compiled and executed successfully.
// Java program to check an item exist in a
// 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(25);
tree.add(30);
if (tree.contains(35))
System.out.println("Item exists.");
else
System.out.println("Item does not exist.");
if (tree.contains(25))
System.out.println("Item exists.");
else
System.out.println("Item does not exist.");
}
}
Output
Item does not exist.
Item exists.
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. And, created a TreeSet collection tree and added integer elements using add() method. Then we used contains() method to check whether a specified item exists in the TreeSet collection or not, and printed the appropriate result.
Java TreeSet Programs »