Java HashMap Get Example

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

How to get a value for the given key from HashMap using the get method?

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

If the key does not exist in the map, the get method returns null.

Output

However, do not rely on the null value to determine whether the key exists in the map object. Since the HashMap class allows null values, the get method can return null if the key is mapped to a null value in the map.

Output

If you want to check if the key exists in the HashMap, you should use the containsKey method instead of the get method as given below.

Output

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

As we have seen in the above example, the get method returns a null value if the key does not exist in the map. If you want to get a provided default value if the key does not exist in the map, you can use the getOrDefault method.

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

Output

This example is a part of the HashMap in Java tutorial.

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

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 *