Using java.util.function.Function, we can pass the function as an argument to the method, and then use apply()it to apply it to the corresponding arguments. Here is an example:
import java.util.function.Function;
public class FunctionDemo {
public static Integer square(Integer x) {
return x * x;
}
public static Integer doSomething(Function<Integer, Integer> func) {
return func.apply(5);
}
public static void main(String[] args) {
System.out.println(doSomething(FunctionDemo::square));
}
}
Additional version with several parameters (passed as an array):
public static Integer sum(Integer[] x) {
Integer result = 0;
for(int i = 0; i < x.length; i++)
result += x[i];
return result;
}
public static void main(String[] args) {
Integer[] arr = {1,2,3,4,5};
System.out.println(doSomething(Play::sum, arr));
}
public static Integer doSomething(Function<Integer[], Integer> func,
Integer[] arr) {
return func.apply(arr);
}
source
share