Make Selenium Easy

getOrDefault() – A Method Of Map Interface In Java

Let’s start with a simple Java program and understand:-

Table of Contents


I have created a Map<Integer, String> and stored some key-value pairs. When I try to get the value of existing keys then it returns as expected but when I try to get the value of non-existing keys, it returns NULL and if you try to perform any action on it then you get NullPointerException.

Map interface provides a method getOrDefault() which allows you to return a default value in case of non-existence of a key in Map. It returns the value to which the specified key is mapped, or if this map contains no mapping for the key.

You can see implementation of getOrDefault() method. It is not difficult to create such a method ourselves but it has been added in utility in Map interface for direct use. It was added in 1.8.

Let’s use above method in above program:-

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

getOrDefault() – A Method Of Map Interface In Java

by Amod Mahajan time to read: 2 min
%d bloggers like this: