How to Search for an element in HashSet in Java

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.

package com.thispointer.java.collections.hashsets;

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<>();
		
		setOfStrs.add("hello");
		setOfStrs.add("abc");
		setOfStrs.add("time");
		setOfStrs.add("Hi");
		setOfStrs.add("abc");
		
		// Search for an element from Hash Set
		
		if(setOfStrs.contains("time"))
		{
			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");
		}
		
	}

}

Ouput:

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

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top