Equivalent for Python's lambda functions in Java?

Can someone please tell me if there is an equivalent for Python's lambda functions in Java?

Answers


Unfortunately, there are no lambdas in Java until Java 8 introduced Lambda Expressions. However, you can get almost the same effect (in a really ugly way) with anonymous classes:

interface MyLambda {
    void theFunc(); // here we define the interface for the function
}

public class Something {
    static void execute(MyLambda l) {
        l.theFunc(); // this class just wants to use the lambda for something
    }
}

public class Test {
    static void main(String[] args) {
        Something.execute(new MyLambda() { // here we create an anonymous class
            void theFunc() {               // implementing MyLambda
                System.out.println("Hello world!");
            }
        });
    }
}

Obviously these would have to be in separate files :(


I don't think there is an exact equivalent, however there are anonymous classes that are about as close as you can get. But still pretty different. Joel Spolsky wrote an article about how the students taught only Java are missing out on these beauties of functional style programming: Can Your Programming Language Do This?.


One idea is based on a generic public interface Lambda<T> -- see http://www.javalobby.org/java/forums/t75427.html .


Yes,

Lambda expressions are introduced in java from java8.

Basic syntax for lambda expressions are:

(parameters)->
{
  statements;
}

Example

(String s)->
{
System.out.println(s);
}

Check this link:

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html


Somewhat similarly to Zifre's, you could create an interface thus

public interface myLambda<In, Out> {
    Out call(In i);
}

to enable you to write, say

Function<MyObj, Boolean> func = new Function<MyObj, Boolean>() {
    public Boolean callFor(myObj obj) {
        return obj.canDoStuff();
    };

MyObj thing = getThing;

if (func.callFor(thing)) {
    doSomeStuff();
} else {
    doOtherStuff();
}

It's still a bit kludgy, yeah, but it has input/output at least.


With the release of Java 8, lambda-expression is now available. And the lambda function in java is actually "more powerful" than the python ones.

In Python, lambda-expression may only have a single expression for its body, and no return statement is permitted. In Java, you can do something like this: (int a, int b) -> { return a * b; }; and other optional things as well.

Java 8 also introduces another interface called the Function Interface. You might want to check that out as well.


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

Need Your Help

Function that creates a timestamp in c#

c# timestamp compact-framework database-agnostic time-precision

I was wondering, is there a way to create a timestamp in c# from a datetime?