- 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
Java Program to check if a particular element exists in HashSet
Use the contains() method to check if a particular element exists −
Set<Integer> hs = new HashSet<Integer>(); hs.add(30); hs.add(67); hs.add(88); hs.add(33); hs.add(54); hs.add(90); hs.add(66); hs.add(79);
To check for let’s say, element 89, use the contains() method −
hs.contains(89));
The following is an example to check if a particular element exists in HashSet −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // create hash set Set<Integer> hs = new HashSet<Integer>(); hs.add(30); hs.add(67); hs.add(88); hs.add(33); hs.add(54); hs.add(90); hs.add(66); hs.add(79); System.out.println("Elements in set = "+hs); System.out.println("Does 89 in the set? "+hs.contains(89)); System.out.println("Does 67 in the set? "+hs.contains(67)); } }
Output
Elements in set = [33, 66, 67, 54, 88, 90, 30, 79] Does 89 in the set? false Does 67 in the set? True
- Related Articles
- Check if a particular element exists in Java LinkedHashSet
- Java Program to check if a particular key exists in TreeMap
- Java Program to check if a particular value exists in TreeMap
- Check if a particular key exists in Java LinkedHashMap
- Check if a particular value exists in Java LinkedHashMap
- Check if a particular value exists in Java TreeSet
- Check for an element in a HashSet in Java
- Java Program to check if a given value exists in a HashMap
- Check if a HashSet contains the specified element in C#
- Check if a file exists in Java\n
- How to check if event exists on element in jQuery?
- How to check if onClick exists on element in jQuery?
- How to check if element exists in the visible DOM?
- How to check if Element exists in c# Selenium drivers?
- Check if a Java HashSet Collection contains another Collection

Advertisements