How to pass Function as parameter to computeIfAbsent method?

Mayur Patil :

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);
Eran :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72330&siteId=1