Additional methods for working with associative arrays (maps) appeared in Java 8
putIfAbsent() adds a key-value pair only if the key was missing:
map.putIfAbsent("a", "Aa");
forEach() takes a function that performs an operation on each element:
map.forEach((k, v) -> System.out.println(v));
compute() creates or updates the current value with the resulting calculation (it is possible to use the key and the current value):
map.compute("a", (k, v) -> String.valueOf(k).concat(v)); // ["a", "aAa"]
computeIfPresent() if the key exists, it updates the current value with the one obtained as a result of the calculation (it is possible to use the key and the current value):
map.computeIfPresent("a", (k, v) -> k.concat(v));
computeIfAbsent() if the key is absent, creates it with the value that is calculated (it is possible to use the key):
map.computeIfAbsent("a", k -> "A".concat(k)); //["a","Aa"]
getOrDefault() in the absence of a key, returns the passed default value:
map.getOrDefault("a", "not found");
merge() takes a key, a value, and a function that merges the passed and current values. If there is no value under the given key, then it writes the transferred value there.
map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"]
Read also:
- Terminal and intermediate stream methods in Java
- Methods in streams in Java
- Parallel processing of streams in Java 8
Comments
Post a Comment