VOOZH about

URL: https://www.geeksforgeeks.org/java/concurrenthashmap-computeifabsent-method-in-java-with-examples/

⇱ ConcurrentHashMap computeIfAbsent() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ConcurrentHashMap computeIfAbsent() method in Java with Examples

Last Updated : 25 Jun, 2021

The computeIfAbsent(Key, Function) method of ConcurrentHashMap class which attempts to compute its value using the given mapping function for specified key if key is not already associated with a value (or is mapped to null) and enter that computed value in map else null.
 

  • If mapping function of this method returns null, then no value is recorded for new key in map.
  • This method is used to atomically update a value for given key in ConcurrentHashMap.
  • If the remapping function throws an exception, the exception is rethrown, and the no mapping is recorded.
  • During computation, modification this map using this method is not allowed because other threads can also uses this map.


Syntax: 
 

public V 
 computeIfAbsent(K key,
 Function<? super K, ? extends V> remappingFunction)


Parameters: This method accepts two parameters: 
 

  • key: key with which the value is to be associated.
  • remappingFunction: function to do the operation on value.


Returns: This method returns current (existing or computed) value associated with the specified key, or null if mapping returns null.
Exception: This method throws:


  • NullPointerException: if the specified key or remappingFunction is null.

  • llegalStateException: if the computation try to do a recursive update to this map that would otherwise never complete.

  • RuntimeException: if the remappingFunction does so, in which case the mapping is unchanged.


Below programs illustrate the computeIfAbsent(Key, Function) method:
Program 1: 
 


Output: 
ConcurrentHashMap :
 {Laptop=55000, Clothes=4400, Pencil=1000, Mobile=5300}
new ConcurrentHashMap :
 {Laptop=55000, PC=60000, Clothes=4400, Pencil=1000, Charger=800, Mobile=5300}

 

Program 2: 
 


Output: 
ConcurrentHashMap : 
{1=1000RS, 2=5009RS, 3=1300RS}
new ConcurrentHashMap :
{1=1000RS, 2=5009RS, 3=1300RS, 4=6000RS}

 

Program 3: To show NullPointerException
 

Comment