How to check whether particular element is present in HashSet

In this article, we will discuss an example on how to search, whether particular element present in HashSet or NOT

 

Searching element from HashSet :

Method signature:

boolean contains(Object o);
  • This method is used to search specified object from invoking collection
  • Returns true, if present; otherwise return false

SearchElementFromHashSet.java

package in.bench.resources.java.collections;

import java.util.HashSet;

public class SearchElementFromHashSet {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> ceo = new HashSet<String>();

		// adding elements to HashSet object
		ceo.add("Sundar Pichai");
		ceo.add("Satya Nadella");  
		ceo.add("Shiv Nadar");  
		ceo.add("Shantanu Narayen");
		ceo.add("Sundar Pichai"); // duplicate object
		ceo.add("Francisco D’Souza");
		ceo.add(null); // null is allowed

		// Iterating using for-loop
		System.out.println("Iterating HashSet\n");
		for(String founder : ceo) {
			System.out.println(founder);
		}


		// searching element
		boolean boolElement = ceo.contains("Sundar Pichai");

		System.out.println("\n\nWhether element 'Sundar Pichai' "
				+ "is present : " + boolElement);

		// searching and printing in same line
		System.out.println("\n\nWhether element 'Shiv Nadar' "
				+ "is present : " + ceo.contains("Shiv Nadar"));

		// searching and printing in same line
		System.out.println("\n\nWhether element 'Nandan Nilekeni' "
				+ "is present : " + ceo.contains("Nandan Nilekeni"));
	}
}

Output:

Iterating HashSet

null
Satya Nadella
Shiv Nadar
Francisco D’Souza
Shantanu Narayen
Sundar Pichai


Whether element 'Sundar Pichai' is present : true


Whether element 'Shiv Nadar' is present : true


Whether element 'Nandan Nilekeni' is present : false

From above example, HashSet

  • allows only unique elements
  • null object is allowed (max of 1)
  • retrieve items in random-order, while iterating

 

References:

 

Happy Coding !!
Happy Learning !!

Comparing two HashSet objects using containsAll() method
retainAll() method explanation with HashSet