Java Utility Library

Java HashSet - contains() Method



The java.util.HashSet.contains() method is used to check whether the set contains the specified element or not. It returns true if the set contains the specified element, else returns false.

Syntax

public boolean contains(Object obj)

Parameters

obj Specify element whose presence in the set need to be tested.

Return Value

Returns true if the set contains the specified element, else returns false.

Exception

NA

Example:

In the example below, the java.util.HashSet.contains() method is used to check the presence of specified element in the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hash set
    HashSet<Integer> MySet = new HashSet<Integer>();

    //populating hash set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //checking the presence of elements
    for(int i = 5; i <= 20; i += 5) {
      if(MySet.contains(i))
        System.out.println(i +" is present in MySet.");
      else
        System.out.println(i +" is NOT present in MySet.");
    }       
  }
}

The output of the above code will be:

5 is NOT present in MySet.
10 is present in MySet.
15 is NOT present in MySet.
20 is present in MySet.

❮ Java.util - HashSet