Make Selenium Easy

putIfAbsent() – A Method Of Map Interface In Java

Previously we saw an important method of Map interface named getOrDefault(). In this post, we will see another important method named putIfAbsent().

Let’s start with an example:-

Output

If I want to add a new key-value pair conditionally then we need to write some lines of code as above.

Now you have a direct method putIfAbsent() in Map interface that has similar implementation as above but now no need to write extra lines of code. It was added in 1.8.

If there is no value currently assosiated with given key then this method will add that key in Map with the given value and return null (You can see the implementation 742 Line no ). If the passed key has associated value then it will return that value.

Table of Contents

Output

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.

putIfAbsent() – A Method Of Map Interface In Java

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