Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hashset
contains
java
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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"));
}
}
Use hashset.contains() function in 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.

RELATED TAGS

hashset
contains
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring