Home Java javaTutorial Lambda expression syntax description in java

Lambda expression syntax description in java

Jan 23, 2017 pm 03:42 PM
java lambda expression

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
Copy after login

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
Copy after login

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;
}
Copy after login

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)
Copy after login

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));
  }
}
Copy after login

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
Copy after login

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);
  }
}
Copy after login


This code will output the following:

   
x = 23
y = 23
this.x = 1
LambdaScopeTest.this.x = 0
Copy after login


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) ->{
      // ....
    };
Copy after login


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);
};
Copy after login


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
Copy after login


This code has been used in two places:

public static void printPersons(List< Person> roster, CheckPerson tester) - Option 3
public void printPersonsWithPredicate(List roster, Predicate tester) —— Option 6

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 is expected, and the same expression is of type Predicate. Like this, the type determined by the type expected by the method is called the target type (in fact, I think the type inference in Scala is more suitable here). The Java compiler determines the type of a lambda expression through the context of the target type or the position where the lambda expression is found. This means that lambda expressions can only be used where the Java compiler can infer the type:

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();
  }
Copy after login


Runnable.run()方法没有返回值,而Callable.call()方法有。

假设我们像下面这样重载了invoke方法:

void invoke(Runnable r) {
   r.run();
 }
 
 <t> T invoke(Callable<t> c) {
   return c.call();
 }
Copy after login


那么在下面的语句中将会调用哪个方法呢:

String s = invoke(() -> "done");

调用的是invoke(Callable),因为这个方法有返回值,而invoke(Runnable)没有返回值。在这种情况下lambda表达式(() -> “done”)的类型是Callable

序列化

如果一个lambda表达式的目标类型还有它调用的参数的类型都是可序列化的,那么lambda表达式也是可序列化的。然而就像内部类一样,强烈不建议对lambda表达式进行序列化。

更多java中lambda表达式语法说明相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

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

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

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

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

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

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

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

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

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

In Java remote debugging, how to correctly obtain constant values ​​on remote servers? In Java remote debugging, how to correctly obtain constant values ​​on remote servers? Apr 19, 2025 pm 01:54 PM

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? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

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

See all articles