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
Remove single element from a HashSet in Java
To remove a single element from a HashSet, use the remove() method.
First, create a HashSet −
HashSet hs = new HashSet();
Now, 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");
Let us now remove an element −
hs.remove("R");
The following is an example to remove a single element from a HashSet −
Example
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("R");
hs.add("S");
hs.add("T");
hs.add("V");
hs.add("W");
hs.add("Y");
hs.add("Z");
System.out.println(hs);
// removing a single element
hs.remove("R");
System.out.println(hs);
// removing another element
hs.remove("W");
System.out.println(hs);
}
}
Output
[R, S, T, V, W, Y, Z] [S, T, V, W, Y, Z] [S, T, V, Y, Z]
Advertisements