Check If Key Exists in Java TreeMap Example

This example shows how to check if a key exists in Java TreeMap using the containsKey method. The example also shows how to check if the custom class key exists in the Java TreeMap object.

How to check if a key exists in the TreeMap object in Java?

The containsKey method of the TreeMap class returns true if the specified key exists in the TreeMap object.

This method returns true if the specified key is mapped to any value in the map object, false otherwise.

Output

How to check if the TreeMap contains a custom class key?

If you are using the custom class objects as the keys of the TreeMap, then the custom class must implement the Comparable interface or a custom comparator must be provided while creating the TreeMap object.

Since this is the requirement of putting custom class object keys in the TreeMap in the first place, you do not need to do anything extra for the containsKey method to work as expected. Let’s have a look at an example of that.

Output

As you can see from the output since our Emp class has already implemented the Comparable interface, the containsKey method worked as expected.

Please also see how to check If a value exists in the TreeMap example.

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

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

References:
Java 8 TreeMap

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 *