A lot of times if a key is not present in Map then it needs to be added to the Map and its value must be computed via another Function.
package org.wesome.java8;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
class Apple {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "1");
map.put(2, "10");
map.put(3, "11");
if (Objects.isNull(map.get(4))) {
map.put(4, convertIntegerToBinaryString(4));
}
System.out.println("map = " + map);
}
private static String convertIntegerToBinaryString(int integer) {
return Integer.toBinaryString(integer);
}
}To avoid the boilerplate if-else code, java 8 introduces computeIfAbsent method, if the key is absent in the Map, then its value will be computed via a Function and the newly generated value will be added to the Map as well.
computeIfAbsent method will modify the existing Map as well
The computeIfAbsent method will be available for all Map Intertface implementing concrete classes such as HashMap, LinkedHashMap and TreeMap ect
package org.wesome.java8;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
class Apple {
public static void main(String[] args) {
Function<Integer, String> function = Integer::toBinaryString;
Map<Integer, String> map = new HashMap<>();
map.put(1, "1");
map.put(2, "10");
map.put(3, "11");
map.computeIfAbsent(4, function);
System.out.println("map = " + map);
}
}if the Mapping Function returns null, in that case no value will be added in the Map