The contains()
method of HashSet
checks if the specified element is present in the HashSet
or not.
The syntax of the contains()
method is shown below:
Hashset.contains(parameter);
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
.
The method returns true
if the specified element is present in the Hashset
. Otherwise, it returns false
.
Let’s take a look at the code now:
import java.util.*;class Solution{public static void main(String args[]){// Creating an Empty HashSetHashSet<String> hashSet = new HashSet<String>();// Use add() methodhashSet.add("Hello");hashSet.add("I");hashSet.add("love");hashSet.add("Coding");// Displaying the HashSetSystem.out.println("HashSet: " + hashSet);// Check for "Coding" in the setSystem.out.println("Does the Set contains 'Coding'? " +hashSet.contains("Coding"));// Check for "Hello" in the setSystem.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"));}}
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.