I am new to Java, kinda transition from C# to Java.
java.util.function has a interface defined as Function which is input to computeIfAbsent method of Map.
I wanted to define and delegate that function to computeIfAbsent method.
map.computeIfAbsent(key, k => new SomeObject())
works but I wanted it with callback where func. But the problem is Function requires input parameter to be defined. How can I set it to void or with no argument.
map.computeIfAbsent(key, func);
computeIfAbsent will always have an input parameter for the passed Function - that would be the key.
Therefore, just as you can write:
map.computeIfAbsent(key, k -> new SomeObject());
you can also write (assuming the key of your Map is a String):
Function<String,SomeObject> func = k -> new SomeObject();
map.computeIfAbsent(key, func);
If func is not computationally expensive and has no side-effects then you can just use putIfAbsent (notice it's 'put', not 'compute') and call the method directly. It is semantically equivalent.
map.putIfAbsent(key, func());
func will be evaluated every time, regardless of whether it's going to be inserted, but provided it's quick then that's not really a problem.
You can just create a lambda that takes the parameter and calls your function, ignoring the parameter.
map.computeIfAbsent(key, k -> func());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With