Skip to content

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.


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.


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.

Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.