23

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

2
  • For what it's worth, five years later, Java 8 has added lambda expressions as a language feature and a new Streams API for dealing with bulk data operations. Not quite comprehensions, but still useful. Commented Apr 26, 2014 at 16:41
  • Check this out: Are Java 8 Lambdas Closures? Commented Jun 5, 2017 at 20:38

7 Answers 7

27

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 :(

5
  • 1
    Lambda can take and will return a value. You want something more like Callable.
    – Dustin
    Commented May 30, 2009 at 17:40
  • 1
    In addition to being able to accept parameters and return values, lambdas can also access local variables in the scope they were defined. In Java, anonymous classes can access final variables in the scope they were defined in, which is similar enough. OTOH, it might be a good idea for Something to implement Callable.
    – elifiner
    Commented May 30, 2009 at 17:48
  • One small quibble: MyLambda doesn't have to be in a different file; you could declare it as an inner, public, static interface of Something. Commented Dec 1, 2011 at 21:20
  • 1
    There's always Jython... :) And Nice is another language that emulates Java, but adds this functionality...
    – Alex
    Commented May 24, 2012 at 7:17
  • 1
    Can you please update the answer taking into account java 8?
    – RBz
    Commented May 9, 2016 at 23:08
9

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?.

6

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

3

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

3

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
1

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.

1
  • I think you're missing a bracket on line 5 of that 2nd code snippet. I tried to add it myself, but Stackoverflow won't let me make modifications of only 1 character in length. Commented May 29, 2017 at 5:32
1

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.