Remove HashSet elements

We can use remove() method of HashSet to remove elements from HashSet collection

boolean remove(Object obj)

Example

  1. import java.util.*;
  2. public class HashSetRemoveExample {
  3.    public static void main(String args[]) {
  4.      
  5.       HashSet<String> hs =  new HashSet<String>();
  6.  
  7.       hs.add("java");
  8.       hs.add("c");
  9.       hs.add("c++");
  10.       System.out.println("HashSet before removing elements");
  11.       System.out.println(hs);
  12.       hs.remove("java");
  13.       System.out.println("HashSet after removing elements");
  14.       System.out.println(hs);
  15.     }
  16. }
import java.util.*;
public class HashSetRemoveExample {
   public static void main(String args[]) {
     
      HashSet<String> hs =  new HashSet<String>();
 
      hs.add("java");
      hs.add("c");
      hs.add("c++");
      System.out.println("HashSet before removing elements");
      System.out.println(hs);
      hs.remove("java");
      System.out.println("HashSet after removing elements");
      System.out.println(hs);
    }
}


Removing all elements at once

We can use clear() method of HashSet to remove all elements in one go

Example

  1. import java.util.*;
  2. public class HashSetRemoveAllExample {
  3.    public static void main(String args[]) {
  4.      
  5.       HashSet<String> hs =  new HashSet<String>();
  6.  
  7.       hs.add("java");
  8.       hs.add("c");
  9.       hs.add("c++");
  10.       System.out.println("HashSet before removing all elements");
  11.       System.out.println(hs);
  12.       hs.clear();
  13.       System.out.println("HashSet after removing all elements");
  14.       System.out.println(hs);
  15.     }
  16. }
import java.util.*;
public class HashSetRemoveAllExample {
   public static void main(String args[]) {
     
      HashSet<String> hs =  new HashSet<String>();
 
      hs.add("java");
      hs.add("c");
      hs.add("c++");
      System.out.println("HashSet before removing all elements");
      System.out.println(hs);
      hs.clear();
      System.out.println("HashSet after removing all elements");
      System.out.println(hs);
    }
}

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on