- HashMap is Hash table based implementation of the Map interface.
- HashMap provides constant-time performance for the basic operations (get and put).
- HashMap based implementation is not thread safe.
- HashMap must synchronized externally, If multiple threads access a hashmap concurrently
- putIfAbsent method is defined in Map interface.
- putIfAbsent method is used to add entry to HashMap, if its not present in HashMap.
Prototype of putIfAbsent method
- default V putIfAbsent(K key, V value)
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
Program – putIfAbsent method of HashMap in java
package org.learn.collection.map.hmap;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class DemoPutIfAbsentHashMap {
public static void main(String[] args) {
Map<String, String> mapSportsPersonality = new HashMap<>();
mapSportsPersonality.put("Tennis", "Federer");
mapSportsPersonality.put("baseball", "Trout");
mapSportsPersonality.put("Basketball", "Jordan");
mapSportsPersonality.put("Golf", "Woods");
System.out.println("Demo of putIfAbsent method: ");
demoPutIfAbsent(mapSportsPersonality);
}
private static void demoPutIfAbsent(Map<String, String> mapSportsPersonality) {
System.out.println("1. Orignal HashMap:" + mapSportsPersonality);
Map.Entry<String, String> newEntry = new AbstractMap.SimpleEntry<String, String>("Tennis", "Djokovic");
System.out.println("2. New entry to add:\n" + newEntry);
String existingValue = mapSportsPersonality.putIfAbsent(newEntry.getKey(), newEntry.getValue());
if (null != existingValue) {
System.out.println("Key :" + newEntry.getKey() + " already exists, Record not inserted");
System.out.println("Entries in hashmap:" + mapSportsPersonality);
} else {
System.out.println("New record added to hashMap:\n"+mapSportsPersonality);
}
newEntry = new AbstractMap.SimpleEntry<String, String>("Boxer", "Ali");
System.out.println("3. New entry to add:\n" + newEntry);
existingValue = mapSportsPersonality.putIfAbsent(newEntry.getKey(), newEntry.getValue());
if (null != existingValue) {
System.out.println("Key :" + newEntry.getKey() + " already exists, Record not inserted");
System.out.println("Entries in hashmap:" + mapSportsPersonality);
} else {
System.out.println("New record added to hashMap:\n" + mapSportsPersonality);
}
}
}
Output – putIfAbsent method of HashMap in java
Demo of putIfAbsent method:
1. Orignal HashMap:{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan}
2. New entry to add:
Tennis=Djokovic
Key :Tennis already exists, Record not inserted
Entries in hashmap:{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan}
3. New entry to add:
Boxer=Ali
New record added to hashMap:
{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan, Boxer=Ali}
Oracle reference