Java 8 - Difference between Map putIfAbsent() and computeIfAbsent

Both functions aspire to add an element if the specified Key is not already present in Map. 

putIfAbsent adds an element with the specified Value whereas computeIfAbsent adds an element with the value computed using the Key.

putIfAbsent

Map<String,String> intMap = new HashMap<String,String>();
intMap.put("Key1","Value1");
intMap.put("Key2", "Value2");
intMap.putIfAbsent("Key3", "Value3");

Map Content : {Key2=Value2, Key1=Value1, Key3=Value3}  

computeIfAbsent

Map<String,String> intMap = new HashMap<String,String>();
intMap.put("Key1","Value1");
intMap.put("Key2", "Value2");
intMap.computeIfAbsent("Key3", e->"Value".concat(e.substring(3,4)));

Map Content : {Key2=Value2, Key1=Value1, Key3=Value3}
   
Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus