Java TreeSet contains(Object o) Example

In this example we will learn how to search if a element is present in the TreeSet or not. We will use the contains(Object o) method of java.util.TreeSet class.

Signature

public boolean contains(Object o)

This method returns true if the TreeSet contains the specified element.

Example

The following example shows the usage of java.util.TreeSet.contains(o) method.

import java.util.TreeSet;

public class ContainsMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet treeSet1 = new TreeSet();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        
        //Checking if Element2 is present or not        
        if(treeSet1.contains("Element2"))
        {
            System.out.println("Element2 is present in the TreeSet");
        }
        else
        {
            System.out.println("Element2 is not present in the TreeSet");
        }
    }
}

Output

Element2 is present in the TreeSet

Leave a Reply

Your email address will not be published. Required fields are marked *