Java8 lambda expression

@H_ 404_ 0 @ overview

Lambda expression is a new feature in Java 8. It can be understood as an anonymous function.

Lambda expressions can be understood as condensing a function into one line of code, making the code more concise and compact.

Lambda expression syntax:

The parameters are as follows:

Lambda expression instance:

// 无参,返回5() -> 5;// 接收参数x,返回2*xx -> 2 * x;// 接收参数x y,返回x+y(x,y) -> x + y;// 指明接收参数类型(int x,int y) -> x + y;// 接收字符串并打印,无返回值(String s) -> System.out.print(s);// 包括函数体(String s) -> { System.out.print(s); return s;  };

In Python. However, everything in Python is an object. You can assign a function to a variable directly. How to use lambda expressions in Java?

It can be seen that the lambda expression actually implements the methods in the interface. How does it feel like an anonymous inner class?

Differences between lambda expressions and anonymous inner classes:

Functioninterface annotation:

@Functioninterface is a newly added interface in Java 8. It is used to indicate that the interface is a functional interface defined according to the Java language specification. For example, the following code:

@FunctionInterfacepublic interface MathOperation{ public int operation(int a,int b);}

If more abstract methods are added to the interface, a compilation error will be thrown.

Variables in lambda expressions

There's nothing wrong with this, but if you want to modify the string later, the problem comes

You can see that the external local variables used in lambda expressions must be final. What about member variables?

Member variables and static variables can be used and modified later. For the reasons, see my article

@H_ 404_ 0@Java Example of lambda expression in

So what convenience can lambda expressions bring to Java? Take a look at the following examples:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>