
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 All Elements from a HashSet in Java
To remove all the elements from HashSet, use the clear() method.
Create a HashSet and initialize elements −
String strArr[] = { "P", "Q", "R", "S" }; Set s = new HashSet(Arrays.asList(strArr));
Now, to remove all the above elements −
s.clear()
The following is an example to remove all elements from a HashSet −
Example
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String[] a) { String strArr[] = { "P", "Q", "R", "S" }; Set s = new HashSet(Arrays.asList(strArr)); strArr = new String[] { "R", "S", "T", "U" }; s.addAll(Arrays.asList(strArr)); System.out.println("Elements = " +s); // removing all elements s.clear(); System.out.println("Set after removing all the elements = " +s); } }
Output
Elements = [P, Q, R, S, T, U] Set after removing all the elements = []
Advertisements