HashSet contains(Object o) method in java

Let’s learn HashSet contains(Object o) method in java.

HashSet contains(Object o) method in java

contains(Object o) method of HashSet class returns true if this set contains the specified element.

More formally, returns true if and only if this set contains an element e such that Objects.equals(o, e).

Syntax:

public boolean contains(Object o)

Parameters:

o element whose presence in this set is to be tested.

Also read – HashSet in java

Now let’s see example on HashSet contains(Object o) method.

import java.util.HashSet;
public class HashSetContainsObjectMethodExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("hello");
      hs.add("world");
      hs.add("java");
      // check if element exists
      boolean bool = hs.contains("world");
      System.out.println("Is element 'world' exists: " + bool);
   }
}


Output:

Is element ‘world’ exists: true