Passing Function as a Parameter in Java

How to pass a function as a parameter in Java?

Java 8 and above

Using Java 8+ lambda expressions, if you have a class or interface with only a single abstract method (sometimes called a SAM type), for example:

public interface MyInterface {
String doSomething(int param1, String param2);
}

then anywhere where MyInterface is used, you can substitute a lambda expression:

class MyClass {
public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}

For example, you can create a new thread very quickly:

new Thread(() -> someMethod()).start();

And use the method reference syntax to make it even cleaner:

new Thread(this::someMethod).start();

Without lambda expressions, these last two examples would look like:

new Thread(new Runnable() { someMethod(); }).start();

Before Java 8

A common pattern would be to 'wrap' it within an interface, like Callable, for example, then you pass in a Callable:

public T myMethod(Callable<T> func) {
return func.call();
}

This pattern is known as the Command Pattern.

Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.

In response to your comment below you could say:

public int methodToPass() { 
// do something
}

public void dansMethod(int i, Callable<Integer> myFunc) {
// do something
}

then call it, perhaps using an anonymous inner class:

dansMethod(100, new Callable<Integer>() {
public Integer call() {
return methodToPass();
}
});

Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.

How to pass a function as a parameter in java

Java 8 was shipped with enormous number of functional interfaces. You can use one of those to describe the expected function to be passed as parameter in your method.

In your case, for passing a function which excepts a single double parameter and applys a logic, use java.util.function.DoubleUnaryOperator:

static double foo(DoubleUnaryOperator fn){
double aNumber = 2.0;
return fn.applyAsDouble(aNumber);
}

And then create a lambda (or an object which implements DoubleUnaryOperator) and pass it to the foo method:

foo(d -> d * 3);

or

public class Fn implements DoubleUnaryOperator {
@Override
public double applyAsDouble(double d) {
return d * 3;
}
}

How to pass a function as an parameter to another function

No, you can't pass methods.

But there is a simple workaround: pass a Runnable.

void myFunction(boolean coondition, Runnable function)
{
if(condition) {
function.run();
}
}

and call it like this: (using the old syntax)

myFunction(condition, new Runnable() {
@Override
public void run() {
otherFunction();
}
});

or using the new lambda syntax in Java 8 (which is mostly shorthand for the above):

myFunction(condition, () -> {otherFunction();}}

Java Pass Method as Parameter

Edit: as of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier...


Take a look at the command pattern.

// NOTE: code not tested, but I believe this is valid java...
public class CommandExample
{
public interface Command
{
public void execute(Object data);
}

public class PrintCommand implements Command
{
public void execute(Object data)
{
System.out.println(data.toString());
}
}

public static void callCommand(Command command, Object data)
{
command.execute(data);
}

public static void main(String... args)
{
callCommand(new PrintCommand(), "hello world");
}
}

Edit: as Pete Kirkham points out, there's another way of doing this using a Visitor. The visitor approach is a little more involved - your nodes all need to be visitor-aware with an acceptVisitor() method - but if you need to traverse a more complex object graph then it's worth examining.

Pass function as reference to another method in Java

Your method can be represented by the Java 8 functional interface BiFunction<T, U, R>, since it takes two arguments and returns a value.

String operate(BiFunction<Value,Value,Boolean> function, TypeOfParam1 param1, TypeOfParam2 param2) {
val1 = some computations on param1
val2 = some other computations on param2
Boolean value = function.apply(val1,val2);
return value ? "Yes" : "No";
}

And call operate with a method reference :

ABC abcInstance = ...
String boolString = operate (abcInstance::getBool, param1, param2);

Pass function as parameter to method and return its return Value in Java?

Well instead of using Runnable you can create your own interface (Runnable is also interface). If you want the return type to be generic you can create something like:

@FunctionalInterface
interface MyCommand<T> {
public T execute();
}

Then your code will become:

public <T> T runCommand(MyCommand<T> command){
if(someCondition){
//Run it in context or whatever
return command.execute();
} else {
return command.execute();
}
}

And you can use it like (full code here):

public class Test{

public static void main(String[] args) {
Test test=new Test();
String result1=test.runCommand(test::stringCommand);
Integer result2=test.runCommand(test::integerCommand);
Boolean result3 = inter.runCommand(new MyCommand<Boolean>() {
@Override
public Boolean execute() {
return true;
}
});
}

public String stringCommand() {
return "A string command";
}

public Integer integerCommand() {
return new Integer(5);
}

public <T>T runCommand(MyCommand<T> command){
return command.execute();
}
}


Related Topics



Leave a reply



Submit