Skip to content

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.

Output

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.

Output

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.

Output

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.

Output

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.

References:
Java 8 HashSet

About the author

Leave a Reply

Your email address will not be published.