Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements