Can someone please tell me if there is an equivalent for Python's lambda functions in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- streaming md5sum of contents of a large remote tar
- How to maintain order of key-value in DataFrame sa
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:
Obviously these would have to be in separate files :(
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.One idea is based on a generic
public interface Lambda<T>
-- see http://www.javalobby.org/java/forums/t75427.html .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:
Output:
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.
Output:
Java:
Output:
And when used as a parameter:
Output:
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?.
Yes,
Lambda expressions are introduced in java from java8.
Basic syntax for lambda expressions are:
Example
Check this link:
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html