Java HashSet contains(Object o) Example

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

Signature

public boolean contains(Object o)

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

Example

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

import java.util.HashSet;

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

Output

Element2 is present in the HashSet

Leave a Reply

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