HashTable putIfAbsent() method in Java with Examples
Last Updated :
30 Sep, 2019
The putIfAbsent(Key, value) method of Hashtable class which allows to map a value to a given key if given key is not associated with a value or mapped to null. A null value is returned if such key-value set is already present in the HashMap.
Syntax:
public V putIfAbsent(K key, V value)
Parameters: This method accepts two parameters:
- key: specifies the key to which the specified value is to be mapped if key is not associated with any value.
- value: specifies the value to be mapped to the specified key.
Returns: This method returns the existing value mapped to the key and returns null if no value is previously mapped to the key.
Exception: This method throws:
- NullPointerException: when the specified parameters are null.
Below programs illustrate the putIfAbsent(Key, value) method:
Program 1:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Map<String, Integer>
table = new Hashtable<>();
table.put( "Pen" , 10 );
table.put( "Book" , 500 );
table.put( "Clothes" , 400 );
table.put( "Mobile" , 5000 );
System.out.println( "hashTable: "
+ table.toString());
String retValue
= String.valueOf(table
.putIfAbsent( "Booklet" , 2500 ));
System.out.println( "Returned value "
+ "for Key 'Booklet' is: "
+ retValue);
System.out.println( "hashTable: "
+ table);
retValue
= String.valueOf(table
.putIfAbsent( "Book" , 4500 ));
System.out.println( "Returned value"
+ " for key 'Book' is: "
+ retValue);
System.out.println( "hashTable: "
+ table);
}
}
|
Output:
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400}
Returned value for Key 'Booklet' is: null
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400, Booklet=2500}
Returned value for key 'Book' is: 500
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400, Booklet=2500}
Program 2: To Show NullPointerException
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Map<Integer, String>
table = new Hashtable<>();
table.put( 1 , "100RS" );
table.put( 2 , "500RS" );
table.put( 3 , "1000RS" );
System.out.println( "hashTable: "
+ table.toString());
try {
table.putIfAbsent( null , "8" );
}
catch (NullPointerException e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output:
hashTable: {3=1000RS, 2=500RS, 1=100RS}
Exception: java.lang.NullPointerException
References: https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#putIfAbsent-K-V-
Share your thoughts in the comments
Please Login to comment...