- 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
Advertisements