What is the HashSet.contains() function in Java?

The contains() method of HashSet checks if the specified element is present in the HashSet or not.

Syntax

The syntax of the contains() method is shown below:

Hashset.contains(parameter);

Parameters

The contains() method takes a single element as a parameter. The type of parameter is the same as the type of HashSet.

We pass the element to check whether or not it is present within the HashSet.

Return value

The method returns true if the specified element is present in the Hashset. Otherwise, it returns false.

Code

Let’s take a look at the code now:

import java.util.*;
class Solution{
public static void main(String args[])
{
// Creating an Empty HashSet
HashSet<String> hashSet = new HashSet<String>();
// Use add() method
hashSet.add("Hello");
hashSet.add("I");
hashSet.add("love");
hashSet.add("Coding");
// Displaying the HashSet
System.out.println("HashSet: " + hashSet);
// Check for "Coding" in the set
System.out.println("Does the Set contains 'Coding'? " +
hashSet.contains("Coding"));
// Check for "Hello" in the set
System.out.println("Does the Set contains 'Hello'? " +
hashSet.contains("Hello"));
// Check if the Set contains "Java"
System.out.println("Does the Set contains 'Java'? " +
hashSet.contains("Java"));
}
}

Explanation

  • In the first line of code, we import the java.util classes to include the HashSet data structure.

  • In line 7, we initiate an empty HashSet of strings.

  • In lines 9 to 11, we insert some strings.

  • In line 15, we display the elements of the HashSet.

  • From lines 17 to 24, we use the contains() function and check if the specified element is present in the HashSet and print the result.

Free Resources