In this article, we will discuss an example on how to search, whether particular element present in HashSet or NOT
1. 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
Related Articles:
- Java – How to get size or length of HashSet ?
- Java – How to delete a element and delete all elements of HashSet ?
- Java – retainAll() method explanation with HashSet
- Java – How to check whether particular element is present in HashSet ?
- Java – Comparing two HashSet objects using containsAll() method
- Java – Adding one HashSet to another HashSet using addAll() method
- Java – Various ways to iterate through HashSet
- Java – How to reverse LinkedHashSet contents ?
- Java – Sorting HashSet contents in ascending and descending order
- Java – How to Sort HashSet in 2 ways ?
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
- https://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html
Happy Coding !!
Happy Learning !!