The computeIfAbsent(Key, Function) method of HashMap class is used to compute the value for a given key using the given mapping function. Store the computed value for the key in Hashmap if the key is not already associated with a value (or is mapped to null) else null.
Syntax:
public V
computeIfAbsent(K key,
Function<? super K, ? extends V> remappingFunction)
Parameters: This method accepts two parameters:
- key : key for which we want to compute value using mapping.
- remappingFunction : function to do the operation on value.
Returns: This method returns the current (existing or computed) value associated with the specified key, or null if mapping returns null.
- If remapping function returns null for a key, then no mapping is recorded for that key.
- At time of computation if 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.
- This method will throw a ConcurrentModificationException if the remapping function modified this map during computation.
Examples of Java HashMap computeIfAbsent() method
Below programs illustrate the computeIfAbsent(Key, Function) method:
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<>();
map.put( "key1" , 10000 );
map.put( "key2" , 55000 );
map.put( "key3" , 44300 );
map.put( "key4" , 53200 );
System.out.println( "HashMap:\n " + map.toString());
map.computeIfAbsent( "key5" , k -> 2000 + 33000 );
map.computeIfAbsent( "key6" , k -> 2000 * 34 );
System.out.println( "New HashMap:\n " + map);
}
}
|
Output
HashMap:
{key1=10000, key2=55000, key3=44300, key4=53200}
New HashMap:
{key1=10000, key2=55000, key5=35000, key6=68000, key3=44300, key4=53200}
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>();
map.put( 10 , "Aman" );
map.put( 20 , "Suraj" );
map.put( 30 , "Harsh" );
System.out.println( "HashMap:\n" + map.toString());
map.computeIfAbsent( 40 , k -> "Sanjeet" );
map.computeIfAbsent( 10 , k -> "Amarjit" );
System.out.println( "New HashMap:\n" + map);
}
}
|
Output
HashMap:
{20=Suraj, 10=Aman, 30=Harsh}
New HashMap:
{20=Suraj, 40=Sanjeet, 10=Aman, 30=Harsh}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!