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:-

package Concepts;

import java.util.HashMap;
import java.util.Map;

public class PutIfAbsentMethodExample {
	
	public static void main(String[] args) {
		
		Map dataMap = new HashMap<>();
		dataMap.put(101,"Amod");
		dataMap.put(102,"Swati");
		dataMap.put(103,"Aaditya");
		dataMap.put(104,"Animesh");
		
		// If we want to first check if a key is present and then add to map if not present
		if(!dataMap.containsKey(105))
			dataMap.put(105, "Suresh");
		
		// Or something as below
		if(dataMap.get(106) == null)
			dataMap.put(106, "Mahesh");
		
		System.out.println(dataMap);
	
	}

}

Output

{101=Amod, 102=Swati, 103=Aaditya, 104=Animesh, 105=Suresh, 106=Mahesh}

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.

package Concepts;

import java.util.HashMap;
import java.util.Map;

public class PutIfAbsentMethodExample {
	
	public static void main(String[] args) {
		
		Map dataMap = new HashMap<>();
		dataMap.put(101,"Amod");
		dataMap.put(102,"Swati");
		dataMap.put(103,"Aaditya");
		dataMap.put(104,"Animesh");
		
		// If we want to first check if a key is present and then add to map if not present
		if(!dataMap.containsKey(105))
			dataMap.put(105, "Suresh");
		
		// Or something as below
		if(dataMap.get(106) == null)
			dataMap.put(106, "Mahesh");
		
		System.out.println(dataMap);
		
		dataMap.putIfAbsent(107, "Sachin");
		dataMap.putIfAbsent(108, "Virat");
		
		System.out.println(dataMap);
	
	}

}

Output

{101=Amod, 102=Swati, 103=Aaditya, 104=Animesh, 105=Suresh, 106=Mahesh}
{101=Amod, 102=Swati, 103=Aaditya, 104=Animesh, 105=Suresh, 106=Mahesh, 107=Sachin, 108=Virat}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *