Certain times the single entire value
or the entire value
of the map
needs to be updated, in the case of a single update, the traditional way is to get the value
based on the key
or for the entire value
, iterate the whole Map
over the entry set
and update each entry
.
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(1);
if (Objects.nonNull(temp) && temp.equals("Macintosh")) {
map.put(1, "MACINTOSH");
}
for (Map.Entry<Integer, String> entry : map.entrySet()) {
entry.setValue(entry.getValue().concat(" Apple"));
}
System.out.println("map = " + map);
}
}
to avoid the boilerplate iteration
loop, Java 8
introduced the replaceAll
method in Map Interface
, it internally iterates over the map and updates the value
corresponding to each key
.
replaceAll method will modify the entire existing Map
The replaceAll
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");
/* Replace a single entry, if key is present and has the old value, then update with the new value */
map.replace(1, "Macintosh", "MACINTOSH");
System.out.println("map = " + map);
/* Replace all the entry with the new value using lambda expression */
map.replaceAll((key, val) -> val + " Apple");
System.out.println("map = " + map);
/* Replace all the entry with the new value using BiFunction */
map.replaceAll(biFunction);
System.out.println("map = " + map);
}
}