Skip to content

How to Remove Element from Java LinkedHashSet Example

This example shows how to remove an element from the LinkedHasSet in Java. This example also shows how to remove an element from LinkedHashSet of custom class objects.

How to remove an element from LinkedHashSet in Java?

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

The remove method returns true if the specified element exists in the LinkedHashSet and it was removed. If the specified object is not found in the set, it returns false.

Output

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

The remove method relies on the equals method to find and remove the element from the LinkedHashSet object. If the custom class has not overridden the equals and hashCode methods, the remove method does not work properly.

Output

As we can see from the output, the object was not removed even if it was present in the LinkedHashSet. To solve the problem of custom class not being removed from the LinkedHashSet, the custom class needs to override the equals and hashCode methods as given below.

Output

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

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

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

References:
Java 8 LinkedHashSet

About the author

Leave a Reply

Your email address will not be published.