We can remove all element from HashSet using clear() method . Clear () method of set removes all of the elements from this set. The set will be empty after this call returns.
Syntax :
public void clear() {
}
Let’s see set clear() method example in java
import java.util.HashSet;
import java.util.Set;
public class RemoveAll {
public static void main(String[] args) {
Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
hs.add("javascript");
hs.add("mysql");
//print hashset
System.out.println("Before Remove element hashset is = "+hs);
/*
* Removes all of the elements fromĀ set
*/
hs.clear();
System.out.println("After Remove elements hashset is ="+hs);
}
}
Output:
Before Remove element hashset is = [javascript, php, html, java, mysql]
After Remove elements hashset is =[]