Write a Java program to check whether an item exists in a TreeSet collection or not


This is a Java program that demonstrates how to check if an item exists in a TreeSet using the contains() method.

The program first creates a TreeSet object called num and adds four integer elements to it using the add() method. Notice that the value 30 is added twice to demonstrate that TreeSet only contains unique elements.

Then, the program uses an if statement to check if the num set contains the value 30. If the set contains the value, the program prints "Item Exists" to the console. If the set does not contain the value, the program prints "Item does Not Exist" to the console.

Source Code

import java.io.*;
import java.util.*;
public class ItemExist
{
	public static void main(String args[]) 
	{
		TreeSet <Integer> num = new TreeSet <Integer>();
		num.add(30);
		num.add(25);
		num.add(30);
		num.add(60);
 
		if(num.contains(30))
		{
			System.out.println("Item Exists");
		}
		else
		{
			System.out.println("Item does Not Exist");
		}
	}
}

Output

Item Exists