How do I use the computeIfAbsent
method? How does it work, and when is it done?
Answer 1, authority 100%
Method computeIfAbsent two parameters are passed: the key
key and the function for calculating the value for this key mappingFunction
.
The logic of the method:
- Check for the presence of such a key in map. If there is a key and the value by the key is not
null
, then we do nothing - Otherwise (there is no key or the key value is
null
), we calculate the value by applyingmappingFunction
tokey
- If the final value is not
null
, then write a key-value pair to 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 , especially if the computed value does not depend on the key at all.
For example, if Map & lt; Integer, List & lt; Integer & gt; & gt; map
you just need to put a new list by key:
map.putIfAbsent (key, new ArrayList & lt; & gt; ());
If, at the same time, you want to immediately put the value in this list, then it will be more convenient here computeIfAbsent
:
map.computeIfAbsent (key, k - & gt; new ArrayList & lt; & gt; ()). add (100);
instead of
map.putIfAbsent (key, new ArrayList & lt; & gt; ());
map.get (key) .add (100);
A good example of using the computeIfAbsent
method to remember the result is to calculate Fibonacci numbers :
private static Map & lt; Integer, Long & gt; map = new HashMap & lt; & gt; ();
static
{
map.put (0, 0L);
map.put (1, 1L);
}
public static long fibonacci (int x)
{
return map.computeIfAbsent (x, n - & gt; fibonacci (n - 2) + fibonacci (n - 1));
}
And call:
System.out.println (fibonacci (10));
55