Skip to content

Check If Element Exists in LinkedHashSet in Java Example

This example shows how to check if an element exists in LinkedHashSet in Java. This example also shows how to check if LinkedHashSet contains the specified element using the contains method.

How to check if an element exists in LinkedHashSet in Java?

The contains method of the LinkedHashSet class returns true if the specified element is found in the LinkedHashSet object.

The contains method returns true if this set object contains the specified element, false otherwise.

Output

How to check if LinkedHashSet contains an object of a custom class?

The LinkedHashSet contains method relies on the equals method of the elements to compare and find the objects.

If the LinkedHashSet elements are objects of a custom class, then the custom class must implement the equals and hashCode methods for the contains method to work properly.

Let’s first see an example of that.

Output

As we can see from the output, even if the specified custom class object was present in the LinkedHashSet, the contains method returned false.

In order to solve the problem of contains method returning false for the custom class objects, we need to override the equals and hashCode methods in the Subject custom class as given below.

Output

As we can see from the output, the LinkedHashSet contains method worked as expected this time.

This example is a part of the LinkedHashSet in Java 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.