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 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中文网!

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software