HashMap putIfAbsent(key, value) method in Java with Examples
Last Updated :
19 Feb, 2021
The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance.
Syntax:
public V putIfAbsent(K key, V value)
Parameters: This method accepts two parameters:
- key: which is the key with which provided value has to be mapped.
- value: which is the value which has to be associated with the provided key, if absent.
Return Value:
This method returns null (if there was no mapping with the provided key before or it was mapped to a null value) or current value associated with the provided key.
Exceptions:
This method can throw the following exceptions:
- NullPointerException: if the specified key or value is null, and this map does not support null value.
- IllegalArgumentException: if the specified key or value is preventing it from being stored in the map.
- UnsupportedOperationException – if the put operation is not supported by this map (optional)
- ClassCastException – if the key or value is of an inappropriate type for this map (optional)
Program 1:
Java
import java.util.HashMap;
public class TestClass {
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<>();
map.put( "a" , 10000 );
map.put( "b" , 55000 );
map.put( "c" , 44300 );
map.put( "e" , 53200 );
System.out.println( "HashMap:\n " + map.toString());
map.putIfAbsent( "d" , 77633 );
System.out.println( "New HashMap:\n " + map);
map.putIfAbsent( "d" , 55555 );
System.out.println( "Unchanged HashMap:\n " + map);
}
}
|
Output
HashMap:
{a=10000, b=55000, c=44300, e=53200}
New HashMap:
{a=10000, b=55000, c=44300, d=77633, e=53200}
Unchanged HashMap:
{a=10000, b=55000, c=44300, d=77633, e=53200}
Program 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<>();
map.put( "a" , 10000 );
map.put( "b" , 55000 );
map.put( "c" , 44300 );
map.put( "e" , null );
System.out.println( "HashMap:\n " + map.toString());
Integer r1 = map.putIfAbsent( "d" , 77633 );
Integer r2 = map.putIfAbsent( "e" , 77633 );
System.out.println( "Value of r1:\n " + r1);
System.out.println( "Value of r2:\n " + r2);
System.out.println( "New HashMap:\n " + map);
}
}
|
Output
HashMap:
{a=10000, b=55000, c=44300, e=null}
Value of r1:
null
Value of r2:
null
New HashMap:
{a=10000, b=55000, c=44300, d=77633, e=77633}
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#putIfAbsent-K-V-
Share your thoughts in the comments
Please Login to comment...