Make Selenium Easy

getOrDefault() – A Method Of Map Interface In Java

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

Table of Contents

Output

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.
#ThanksForReading
#HappyLearning

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

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

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
0
%d bloggers like this: