Open In App

Java HashSet contains() Method

Last Updated : 08 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The contains() method of the HashSet class in Java is used to check if a specific element is present in the HashSet or not. So, mainly it is used to check if a set contains any particular element.

Java
// Java program to demonstrates the working of contains()
import java.util.*;

public class Geeks {
    public static void main(String[] args)
    {
        // Create a HashSet
        HashSet<Integer> hs = new HashSet<Integer>();

        // Add elements to HashSet
        hs.add(1);
        hs.add(2);
        hs.add(3);

        System.out.println("HashSet:" + hs);

        System.out.println("HashSet Contains 2: "
                           + hs.contains(2));
        System.out.println("HashSet Contains 10: "
                           + hs.contains(10));
    }
}

Output
HashSet:[1, 2, 3]
HashSet Contains 2: true
HashSet Contains 10: false

Syntax of HashSet contains() Method

boolean contains(Object o)

  • Parameter: The object "o" to be checked for presence in the HashSet.
  • Return Type: This method returns "true" if the specified element is present in the set otherwise, it returns "false".

Next Article

Similar Reads