A lot of times if a key
is present in Map
then it needs to be updated with a new value which 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, "Macintosh");
map.put(2, "Fuji");
map.put(3, "Gala");
map.put(4, "Jonagold");
String temp = map.get(4);
if (Objects.nonNull(temp)) {
temp = temp.concat(" Apple");
map.put(4, temp);
}
System.out.println("map = " + map);
}
}
To avoid the boilerplate if-else
code java 8
introduces computeIfPresent
method, if the key
is present in the Map
, then its value will be computed via BiFunction
which will take key
and value
, and the newly generated value
will be added to the Map
as well.
computeIfPresent method will modify the existing Map as well
computeIfPresent
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.BiFunction;
class Apple {
public static void main(String[] args) {
BiFunction<Integer, String, String> biFunction = (key, value) -> value + " Apple";
Map<Integer, String> map = new HashMap<>();
map.put(1, "Macintosh");
map.put(2, "Fuji");
map.put(3, "Gala");
map.put(4, "Jonagold");
map.computeIfPresent(3, (key, val) -> val + " Apple");
map.computeIfPresent(4, biFunction);
System.out.println("map = " + map);
}
}