In this article we will discuss how to search for an element in HashSet.

Main feature of a HashSet is Fast searching. Which it achieves using Hashing. Now suppose we want to search if an element exists in HashSet ?

It can be done using contains() member function of HashSet i.e.

// It checks if the given element exists in a HashSet or not.
public boolean contains(Object o)

It will first calculate the Hash Code of given object. Then based on that hash code, it will go to a bucket and check all elements inside the bucket using thier equals() member function.

Now Lets see an example to check if a given element exists in a HashSet i.e.


import java.util.HashSet;
import java.util.Iterator;

public class Example2 {

	public static void main(String[] args) {
		// Create a HashSet of String Objects
		HashSet<String> setOfStrs = new HashSet<>();
		// Search for an element from Hash Set
			System.out.println("Yes Set contains the 'time' String");
		if(setOfStrs.contains("table") == false)
			System.out.println("No Set do not contains the 'table' String");


Yes Set contains the 'time' String
No Set do not contains the 'table' String


Join a list of 2000+ Programmers for latest Tips & Tutorials