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

RahimV

RahimV

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 *