Can someone please tell me if there is an equivalent for Python\'s lambda functions in Java?
As already pointed out, lambda expressions were introduced in Java 8.
If you're coming from python, C# or C++, see the excellent example by Adrian D. Finlay, which I personally found much easier to understand than the official documentation.
Here's a quick peek based on Adrian's example, created using a jupyter notebook with the python kernel and IJava java kernel.
Python:
# lambda functions
add = lambda x, y : x + y
multiply = lambda x, y : x * y
# normal function. In python, this is also an object.
def add_and_print_inputs(x, y):
print("add_and_print inputs : {} {}".format(x,y))
return x + y
print(add(3,5), multiply(3,5), add_and_print_inputs(3,5))
Output:
add_and_print inputs : 3 5
8 15 8
Java lambda functions can be multiline, whereas in python they are a single statement. However there is no advantage here. In python, regular functions are also objects. They can be added as parameters to any other function.
# function that takes a normal or lambda function (myfunc) as a parameter
def double_result(x,y,myfunc):
return myfunc(x,y) * 2
double_result(3,5,add_and_print_inputs)
Output:
add_and_print inputs : 3 5
16
Java:
// functional interface with one method
interface MathOp{
int binaryMathOp(int x, int y);
}
// lambda functions
MathOp add = (int x, int y) -> x + y;
MathOp multiply = (int x, int y) -> x * y;
// multiline lambda function
MathOp add_and_print_inputs = (int x, int y) -> {
System.out.println("inputs : " + x + " " + y);
return x + y;};// <- don't forget the semicolon
// usage
System.out.print("" +
add.binaryMathOp(3,5) + " " +
multiply.binaryMathOp(3,5) + " " +
add_and_print_inputs.binaryMathOp(3,5))
Output:
inputs : 3 5
8 15 8
And when used as a parameter:
// function that takes a function as a parameter
int doubleResult(int x, int y, MathOp myfunc){
return myfunc.binaryMathOp(x,y) * 2;
}
doubleResult(3,5,add_and_print_inputs)
Output:
inputs : 3 5
16