Java HashSet Remove Elements Example

This example shows how to remove elements from HashSet in Java. The example also shows how to remove objects of a custom class using the remove method.

How to remove elements from HashSet in Java using the remove method?

The remove method of the HashSet class removes the specified element from the set object.

The remove method returns true if the specified object is found and removed, false otherwise.


How to remove objects of a custom class from the HashSet?

Let’s first see an example of removing a custom class object from the HashSet.


As we can see from the output, even if the Student object with id 2 was present in the HashSet object, the remove method returned false and it was not removed from the HashSet object.

The HashSet remove method relies on the equals method to compare and find the objects to remove. The equals method is not implemented by the Student custom class, so the equals method inherited from the Object class is used which compares the object references. Since the references were different, the remove method could not find the specified object and hence it returned false.

To solve this problem, we need to implement the equals and hashCode methods in our Student custom class as given below.


As we can see from the output, the remove method worked as expected this time and removed the specified object from the HashSet.

Tip: Implement the equals method and hashCode method properly to solve the problem of HashSet not removing elements.

How to remove all elements from the HashSet?

To remove all elements from the HashSet, we can either use the clear method or removeAll method as given below.


Please visit how to clear or remove all elements from the HashSet example to know more.

This example is a part of the Java HashSet Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 HashSet

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *