Which is the Best Java Web Framework ?

Java 8 - Map.put() vs Map.putIfAbsent()

put method inserts the element ( key value pair ) into the Map. If the Map already contains an element with the same Key, the value is overwritten with the new element value.

putIfAbsent performs the check to see if the same Key already existed in the Map and will only all a new element if it's not already there ( Match by the Key )

Sample Code

Map<String,String> intMap = new HashMap<String,String>();

Map Content - {Key2=Value2, Key1=Value1}

Now If we attempt to insert again a new element with the same key


Map Content would be : {Key2=Value2, Key1=Value3} ( Key1 value replaced )

If we attempt to insert a new element using 

intMap.putIfAbsent("Key1", "Value4");

Map Content would be : {Key2=Value2, Key1=Value3} ( Same as the previous content )    
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


Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.