putIfAbsent(K, V): This method is available in java.util.Hashtable class of Java.
Syntax:
V java.util.Hashtable.putIfAbsent(K key, V value)
This method takes two arguments. If the specified key is not already associated with a value associates it with the given value and returns null, else returns the current value.
Parameters: Two parameters are required for this method.
key: key with which the specified value is to be associated.
value: value to be associated with the specified key.
Returns: the previous value associated with the specified key, or null if there was no mapping for the key.
Exceptions: NA
Approach
Java
import java.util.Hashtable;public class HashtableputIfAbsent {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);hashtable.putIfAbsent("Java", 3);System.out.println(hashtable);}}
Output:
{Java=3, World=2, Hello=1}
No comments:
Post a Comment