Java TreeMap Get Method Example

This example shows how to get a value for a key from TreeMap using the get method in Java. This example also shows how to get the default value for a key if the key does not exist using the getOrDefault method.

How to get a value for a key from TreeMap using the get method in Java?

The get method of the TreeMap class returns a value mapped to a given key in the TreeMap object.

The get method returns the value associated with the key if the key exists in the Treemap. If the key does not exist, the get method returns null.

Output

As you can see from the output, the get method returns null if the specified key does not exist in the map object. However, it may also return null if the specified key is mapped to a null value.

Output

For this reason, do not use the get method to check if the key exists in the TreeMap as it produces unreliable results in case there are null values in the map. Instead, always use the containsKey method for checking the existence of the key.

How to get a default value if the key does not exist using the getOrDefault method?

The getOrDefault method returns the specified value if the given key does not exist in the TreeMap object.

The getOrDefault method returns a value mapped to a key if the key exists in the map. If it does not exist, the getOrDefault method returns the specified default value.

Output

As you can see from the example, the getOrDefault method returned the “Default” string for the key 4 which does not exist in the TreeMap object.

Please also visit how to add new key-value mappings to the TreeMap object example to know more.

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 *

Online Shopping