Let’s learn HashMap computeIfAbsent() method in java.
HashMap computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) method in java
computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) method returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.
If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
If the mapping function returns null, no mapping is recorded. If the mapping function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded.
This method will throw a ConcurrentModificationException if it is detected that the mapping function modifies this map during computation.
Syntax
public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
Parameters
key key with which the specified value is to be associated
mappingFunction the mapping function to compute a value
Throws
ConcurrentModificationException – if it is detected that the mapping function modified this map
Example
import java.util.*; class HashMapComputeIfAbsentDemo { public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<>(); hm.put("hello", 15000); hm.put("world", 24000); hm.put("core", 14300); hm.put("java", 61600); System.out.println("HashMap : " + hm.toString()); // value for new key which is absent using computeIfAbsent method hm.computeIfAbsent("abc", k -> 6000 + 12000); hm.computeIfAbsent("xyz", k -> 1000 * 14); // print new mapping System.out.println("New HashMap : " + hm); } }
Output:
HashMap : {core=14300, world=24000, java=61600, hello=15000}
New HashMap : {core=14300, abc=18000, world=24000, java=61600, xyz=14000, hello=15000}
import java.util.*; class HashMapComputeIfAbsentDemo { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<>(); hm.put(15, "hello"); hm.put(24, "world"); hm.put(60, "java"); System.out.println("HashMap : " + hm.toString()); // value for new key which is absent using computeIfAbsent() method hm.computeIfAbsent(20, k -> "core"); // no effect because key 15 is present hm.computeIfAbsent(15, k -> "abc"); System.out.println("New HashMap : " + hm); } }
Output:
HashMap : {24=world, 60=java, 15=hello}
New HashMap : {20=core, 24=world, 60=java, 15=hello}
Also read – abstraction in java