Lambda expression syntax description in java
Syntax Description
A lambda expression consists of the following parts:
1. A comma-separated list of formal parameters in parentheses. The CheckPerson.test method contains a parameter p, which represents an instance of the Person class. Note: The type of the parameter in the lambda expression can be omitted; in addition, if there is only one parameter, even the parentheses can be omitted. For example, the code mentioned in the previous section:
p -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25
2. Arrow symbol: ->. Used to separate parameters and function bodies.
3. Function body. Consists of an expression or block of code. In the example in the previous section, such an expression was used:
p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25
If an expression is used, the Java runtime will calculate and return the value of the expression. In addition, you can also choose to use the return statement in the code block:
p -> { return p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25; }
However, the return statement is not an expression. In lambda expressions, statements need to be enclosed in curly braces. However, there is no need to enclose statements in curly braces when just calling a method that returns a null value, so the following writing is also correct:
email -> System.out.println(email)
lambda expressions and method declarations look a lot alike. Therefore, lambda expressions can also be regarded as anonymous methods, that is, methods without defined names.
The lambda expressions mentioned above are all expressions that use only one parameter as a formal parameter. The following instance class, Caulator, demonstrates how to use multiple parameters as formal parameters:
package com.zhyea.zytools; public class Calculator { interface IntegerMath { int operation(int a, int b); } public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String... args) { Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } }
The operateBinary method in the code uses two integer parameters to perform arithmetic operations. The arithmetic operation here itself is an instance of the IntegerMath interface. In the above program, two arithmetic operations are defined using lambda expressions: addition and subtraction. The execution program will print the following content:
40 + 2 = 42 20 - 10 = 10
Accessing local variables of external classes
Similar to local classes or anonymous classes, lambda expressions can also access local variables of external classes. The difference is that there is no need to consider issues such as overwriting when using lambda expressions. A lambda expression is just a lexical concept, which means it does not need to inherit any name from a superclass, nor does it introduce new scope. That is, a declaration within a lambda expression has the same meaning as a declaration in its external environment. This is demonstrated in the following example:
package com.zhyea.zytools; import java.util.function.Consumer; public class LambdaScopeTest { public int x = 0; class FirstLevel { public int x = 1; void methodInFirstLevel(int x) { //如下的语句会导致编译器在statement A处报错“local variables referenced from a lambda expression must be final or effectively final” // x = 99; Consumer<integer> myConsumer = (y) ->{ System.out.println("x = " + x); // Statement A System.out.println("y = " + y); System.out.println("this.x = " + this.x); System.out.println("LambdaScopeTest.this.x = " + LambdaScopeTest.this.x); }; myConsumer.accept(x); } } public static void main(String... args) { LambdaScopeTest st = new LambdaScopeTest(); LambdaScopeTest.FirstLevel fl = st.new FirstLevel(); fl.methodInFirstLevel(23); } }
This code will output the following:
x = 23 y = 23 this.x = 1 LambdaScopeTest.this.x = 0
If the parameter y in the lambda expression myConsumer in the example is replaced with x, the compiler will report an error:
Consumer<integer> myConsumer = (x) ->{ // .... };
The compiler error message is : "variable x is already defined in method methodInFirstLevel(int)", which means that variable x has been defined in method methodInFirstLevel. The error is reported because lambda expressions do not introduce new scopes. Therefore, you can directly access the field fields, methods and formal parameters of the external class in lambda expressions. In this example, the lambda expression myConsumer directly accesses the formal parameter x of the method methodInFirstLevel. When accessing members of external classes, you also use the this keyword directly. In this example this.x refers to FirstLevel.x.
However, like local classes or anonymous classes, lambda expressions can only access local variables or external members that are declared final (or equivalent to final). For example, we remove the comment before "x=99" in the methodInFirstLevel method in the sample code:
//如下的语句会导致编译器在statement A处报错“local variables referenced from a lambda expression must be final or effectively final” x = 99; Consumer<integer> myConsumer = (y) ->{ System.out.println("x = " + x); // Statement A System.out.println("y = " + y); System.out.println("this.x = " + this.x); System.out.println("LambdaScopeTest.this.x = " + LambdaScopeTest.this.x); };
Because the value of parameter x is modified in this statement, methodInFirstLevel The parameter x can no longer be considered final. Therefore, the Java compiler will report an error like "local variables referenced from a lambda expression must be final or effectively final" where the lambda expression accesses the local variable x.
Target type
How to determine the type of lambda expression. Let’s take a look at the code for screening military service-age personnel:
p -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25
This code has been used in two places:
public static void printPersons(List< Person> roster, CheckPerson tester) - Option 3
public void printPersonsWithPredicate(List
When calling the printPersons method, this The method expects a parameter of type CheckPerson, and the above expression is an expression of type CheckPerson. When calling the printPersonsWithPredicate method, a parameter of type Predicate
Variable declaration;
Assignment;
Return statement;
Array initialization;
Method or constructor parameters;
lambda expression method body;
Conditional expression (?:);
When an exception is thrown.
Target type and method parameters
对于方法参数,Java编译器还需要依赖两个语言特性来决定目标类型:重载解析和类型参数推断。
看一下下面的这两个函数式接口( java.lang.Runnable and java.util.concurrent.Callable
public interface Runnable { void run(); } public interface Callable<v> { V call(); }
Runnable.run()方法没有返回值,而Callable.call()方法有。
假设我们像下面这样重载了invoke方法:
void invoke(Runnable r) { r.run(); } <t> T invoke(Callable<t> c) { return c.call(); }
那么在下面的语句中将会调用哪个方法呢:
String s = invoke(() -> "done");
调用的是invoke(Callable
序列化
如果一个lambda表达式的目标类型还有它调用的参数的类型都是可序列化的,那么lambda表达式也是可序列化的。然而就像内部类一样,强烈不建议对lambda表达式进行序列化。
更多java中lambda表达式语法说明相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

Start Spring using IntelliJIDEAUltimate version...

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

Questions and Answers about constant acquisition in Java Remote Debugging When using Java for remote debugging, many developers may encounter some difficult phenomena. It...

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...
