How to use the computeIfAbsent method? How does it work, and in what case is it performed?
1 answer
The computeIfAbsent method is passed two parameters: the key key and the function for calculating the value of this key mappingFunction .
The logic of the method:
- We check the presence of such a key in the map. If the key is and the value by the key is not
null, then we do nothing - Otherwise (no key or key value is
null), consider the value by applyingmappingFunctiontokey - If the final value is not
null, then write the key-value pair to the map
In the form of code, this logic is described in the documentation as follows:
if (map.get(key) == null) { V newValue = mappingFunction.apply(key); if (newValue != null) map.put(key, newValue); } In some situations, the putIfAbsent method will suffice , especially if the calculated value does not depend on the key at all.
For example, if in Map<Integer, List<Integer>> map you just need to put a new list by key:
map.putIfAbsent(key, new ArrayList<>()); Now, if you want to immediately put the value in this list, then computeIfAbsent more convenient:
map.computeIfAbsent(key, k -> new ArrayList<>()).add(100); instead
map.putIfAbsent(key, new ArrayList<>()); map.get(key).add(100); A good example of using the computeIfAbsent method with memorizing the result is the calculation of Fibonacci numbers :
private static Map<Integer, Long> map = new HashMap<>(); static { map.put(0, 0L); map.put(1, 1L); } public static long fibonacci(int x) { return map.computeIfAbsent(x, n -> fibonacci(n - 2) + fibonacci(n - 1)); } And the challenge:
System.out.println(fibonacci(10)); 55
- And if the key exists and value == null? - alex safsafsd
- @alexsafsafsd so it refers to "Otherwise" - Regent