Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Function as parameter to computeIfAbsent method?

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);
like image 629
Mayur Patil Avatar asked Feb 18 '19 09:02

Mayur Patil


3 Answers

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);
like image 50
Eran Avatar answered Oct 18 '22 20:10

Eran


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.

like image 2
Michael Avatar answered Oct 18 '22 18:10

Michael


You can just create a lambda that takes the parameter and calls your function, ignoring the parameter.

map.computeIfAbsent(key, k -> func());
like image 3
daniu Avatar answered Oct 18 '22 20:10

daniu