java.util.HashMap putIfAbsent()
Description
In dealing with HashMap methods, as a general rule you must always watch out for Generics such that if we have declared our map like HashMap<Integer,String> map = new HashMap<Integer,String>(); then the returned keys are expected to be Integer object type or its subclass and the values as String.
Important notes for putIfAbsent() method:
- specified by putIfAbsent in interface Map<K,V>
Method Syntax
public V putIfAbsent(K key, V value)
Method Argument
Data Type | Parameter | Description |
---|---|---|
K | key | key with which the specified value is to be associated |
V | value | value to be associated with the specified key |
Method Returns
The putIfAbsent() method returns the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key, if the implementation supports null values.)
Compatibility
Requires Java 1.2 and up
Java HashMap putIfAbsent(K key, V value) Example
Below is a java code demonstrates the use of putIfAbsent() method of HashMap class. The example presented might be simple however it shows the behavior of the putIfAbsent() method.
package com.javatutorialhq.java.examples; import static java.lang.System.*; import java.util.HashMap; /* * This example source code demonstrates the use of * putIfAbsent() method of HashMap class */ public class HashMapPutIfAbsentExample { public static void main(String[] args) throws InterruptedException { // get the hashmap object from the method init() HashMap<Integer, String> map = init(); // put a new value to our map object String result = map.putIfAbsent(73654, "Darwin Bocalbos"); /* * code logic to test if the values has been inserted * to the student database. */ if(result!=null){ out.println("Id number taken of "+result); } else{ out.println("Successfully inseerted to the database"); } } private static HashMap<Integer, String> init() { // declare the hashmap HashMap<Integer, String> mapStudent = new HashMap<>(); // put contents to our HashMap mapStudent.put(73654, "Shyra Travis"); mapStudent.put(98712, "Sharon Wallace"); mapStudent.put(71245, "Leo Batista"); return mapStudent; } }
This example is a lot simpler than it looks. First we have a method init() which generally populates a HashMap object and returned. This method has been called by the main method and then we have tried inserting a new value to the key-value pair mapping by using the putIfAbsent() method. To test the returned value we have introduced a code block to check if the returned string is null which means a successful insertion/addition of value, otherwise we print the existing student which currently uses the student id we are trying to add.