Check If Element Exists in TreeSet in Java Example

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

How to check if the specified element exists in the TreeSet in Java?

The contains method of the TreeSet returns true if the specified element exists in the set object.

The contains method returns true if the TreeSet contains the specified element, false otherwise.

Output

What about the TreeSet of custom class objects?

The contains method works for TreeSet of custom class elements too. But remember, if the TreeSet elements are objects of a custom class, then the custom class must implement the Comparable interface or a custom Comparator must be provided in the TreeSet constructor. If not, the code throws java.lang.ClassCastException when we try to add elements to the TreeSet object.

Output

As we can see from the output, the contains method worked just fine for the objects of a custom class.

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

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

References:
Java 8 TreeSet

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 *

Online Shopping