What is the putIfAbsent method in Java HashMaps?
putIfAbsent() is a built-in method defined in the HashMap class in Java. The class is available in the java.util package.
The following is the method prototype:
public V putIfAbsent(K key, V value)
Functionality
A HashMap is a data structure that stores data in the form of key-value pairs. Each unique key is mapped onto one or more data values.
The putIfAbsent() method is used to insert the given key-value pair into the HashMap if the associated key is not already present or mapped onto a null value.
Its functionality is similar to the put() method of HashMaps, but with the added check described above.
Parameters and return value
The method takes the following as input arguments:
-
key: The key to be inserted into the HashMap. -
value: The value to be associated with the provided key.
Note: The types of the key and value must match the key-value types of the HashMap.
The putIfAbsent() method may return the following:
-
nullin case of successful insertion. -
The current value associated with the key in case it already exists within the HashMap.
Code
import java.util.HashMap;public class Main{public static void main(String args[]){// Creating a new HashMapHashMap<Integer, String> hash_map = new HashMap<>();// Mapping String values to Integer keyshash_map.put(2, "Edpresso");hash_map.put(4, "Shots");hash_map.put(6, "of");hash_map.put(8, "Dev");hash_map.put(10, "Knowledge");// Displaying the HashMapSystem.out.println("HashMap: \n" + hash_map);// Mapping new value to a new keyhash_map.putIfAbsent(3, "Concise");// Mapping new value to exisiting keyString value = hash_map.putIfAbsent(8, "Developer");// Printing current value for keySystem.out.println("\nCurrent value: \n" + value);// Displaying the Updated HashMapSystem.out.println("\nUpdated HashMap: \n" + hash_map);}}
Free Resources