- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check for an element in a HashSet in Java
To check whether an element is in a HashSet or not in Java, use the contains() method.
Create a HashSet −
HashSet hs = new HashSet();
Add elements to it −
hs.add("R"); hs.add("S"); hs.add("T"); hs.add("V"); hs.add("W"); hs.add("Y"); hs.add("Z");
To check for an element, for example, S here, use the contains() −
hs.contains("S")
The following is an example to check for an element in a HashSet −
Example
import java.util.*; public class Demo { public static void main(String args[]) { HashSet hs = new HashSet(); // add elements to the HashSet hs.add("R"); hs.add("S"); hs.add("T"); hs.add("V"); hs.add("W"); hs.add("Y"); hs.add("Z"); System.out.println("Set = "+hs); System.out.println("Is character S part of the set? "+hs.contains("S")); System.out.println("Is character B part of the set? "+hs.contains("B")); } }
Output
Set = [R, S, T, V, W, Y, Z] Is character S part of the set? true Is character B part of the set? false
- Related Articles
- Java Program to check if a particular element exists in HashSet
- Remove single element from a HashSet in Java
- Check if a HashSet contains the specified element in C#
- Remove specified element from HashSet in Java
- Find maximum element of HashSet in Java
- Find minimum element of HashSet in Java
- Check whether two HashSet are equal in Java
- Check whether a HashSet is empty or not in Java
- Check if a HashSet and a specified collection share common element in C#
- Convert elements in a HashSet to an array in Java
- Convert an ArrayList to HashSet in Java
- Check existence of an element in Java ArrayList
- Check if a Java HashSet Collection contains another Collection
- HashSet in Java
- Traverse through a HashSet in Java

Advertisements