Home > Java > javaTutorial > body text

Detailed explanation of Lambda expressions in Java examples

WBOY
Release: 2022-04-24 12:04:48
forward
2091 people have browsed it

This article brings you relevant knowledge about java, which mainly introduces issues related to Lambda expressions. Lambda expressions introduce an operator in the Java language**" ->”**, this operator is called Lambda operator or arrow operator. Let’s take a look at it. I hope it will be helpful to everyone.

Detailed explanation of Lambda expressions in Java examples

Recommended learning: "java Video Tutorial"

1. First introduction to Lambda

We know that in Java, interfaces cannot be instantiated, but interfaces An object can point to its implementation class object. What if the interface doesn't even have an implementation object? You can also use anonymous classes, as follows:

public class JavaTest {
    public static void main(String[] args) {
        Fly fly = new Fly() {
            @Override
            public void fly(String name) {
                System.out.println(name + "飞行");
            }
        };
        fly.fly("张三");
    }}interface Fly{
    abstract void fly(String name);}
Copy after login

However, using the anonymous internal method, the amount of code is actually not very concise. In order to make the code more concise, Java introduced Lambda Expression writing uses simpler syntax to achieve this function. The simplified code using Lambda expressions is as follows:

public class JavaTest {
    public static void main(String[] args) {
        Fly fly = name -> System.out.println(name + "飞行");
        fly.fly("张三");
    }}interface Fly{
    abstract void fly(String name);}
Copy after login

The same effect is achieved through Lambda expressions, but the amount of code is streamlined. That's right, this is the charm of Lambda expressions.

2. Functional interface

Before learning the syntax of Lambda expressions, you must first know what functional interface has only one method to be implemented The interface is called a functional interface.

//接口中只有一个待实现的方法 fly,所以这是函数式接口interface Fly{
     void fly(String name);}//接口中有两个待实现的方法 这是不是函数式接口interface Run{
    void fastRun();
    void slowRun();}//接口中有两个方法,但其中一个是已经定义好的default方法,真正需要子类去实现的方法只有一个 这是函数式接口interface Jump{
    void jump();
    default void highJump(){
        System.out.println("跳的更高");
    }}
Copy after login

You can add the **@FunctionalInterface annotation on the interface to assert that the interface is a functional interface. If the interface is not a functional interface, the compilation will prompt an error.
Detailed explanation of Lambda expressions in Java examples
Why do you need to know what a functional interface is? Because Lambda expressions simplify the anonymous class implementation of an interface, it only
works on functional interfaces**.
This is easy to understand. If an interface has multiple methods to be implemented, the Lambda expression cannot tell which method in the interface it is implementing.

3. Lambda expression syntax

Lambda expression introduces an operator **"->"** in the Java language, which is Called Lambda operator or arrow operator. It divides Lambda into two parts:

The left side: specifies all the parameters required by the Lambda expression
The right side: formulates the Lambda body, that is, the function to be performed by the Lambda expression.
Like this:

(parameters) -> expression
或
(parameters) ->{ statements; }
Copy after login

Except for -> and Lambda body, other parameters of Lambda expressions, such as parameters, parentheses, and square brackets, can be omitted based on the parameter type and method body code line number. .
Take the implementation of the following functional interface as an example:

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

    interface GreetingService {
        void sayMessage(String message);
    }

    private int operate(int a, int b, MathOperation mathOperation){
        return mathOperation.operation(a, b);
    }
    
    interface NoParam{
        int returnOne();
    }
Copy after login

The following are the important characteristics of lambda expressions:

  • Optional type declaration: Lambda The expression does not need to declare the parameter type of the implementation method, and the compiler can uniformly identify parameter values.
        // 类型声明
        MathOperation addition = (int a, int b) -> a + b;
        // 不用类型声明
        MathOperation subtraction = (a, b) -> a - b;
Copy after login
  • Optional parameter parentheses: A parameter does not need to be defined with parentheses, but no parameters or multiple parameters need to be defined with parentheses.
      // 不用括号
        GreetingService greetService1 = message ->
                System.out.println("Hello " + message);

        // 用括号
        GreetingService greetService2 = (message) ->
                System.out.println("Hello " + message);
Copy after login
  • Optional braces: If the body contains a statement, braces are not required.
     // 多条语句不可以省略大括号
        MathOperation multiplication = (int a, int b) -> {
            int num = a+1;
            num = a + b;
            return a * b + num;
        };

        // 单条语句可以省略大括号
        MathOperation pision = (int a, int b) -> a / b;
Copy after login
  • Optional return keyword: If the body has only one expression return value, the compiler will automatically return the value. The curly braces need to specify the expression to return. A numerical value.
  // 多条语句的Lambda表达式如果有返回值,需要使用return
        MathOperation multiplication = (int a, int b) -> {
            int num = a+1;
            num = a + b;
            return a * b + num;
        };

        // 单条语句可以省略return
        MathOperation pision = (int a, int b) -> a / b;
Copy after login

4. Scope of use of Lambda expressions

Lambda expressions are not just used to simplify the creation of an anonymous class, it has more uses.

1. Assign values ​​to variables

In the above, the usage of Lambda expressions is to assign values ​​to variables. This can simplify the code segment of anonymous inner class assignment and improve reading efficiency.

MathOperation subtraction = (a, b) -> a - b;
Copy after login

2. As return result

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

    MathOperation getOperation(int a, int b){
        return (a1, b1) -> a+b;
    }
Copy after login

3. As array element

MathOperation math[] = {
                (a,b) -> a+b,
                (a,b) -> a-b,
                (a,b) -> a*b        };
Copy after login

4. As parameter of ordinary method or constructor method

public static void main(String args[]){

        Java8Tester java8Tester = new Java8Tester();
        java8Tester.operate(1,2,((a, b) -> a*b));

    }

    private int operate(int a, int b, MathOperation mathOperation){
        return mathOperation.operation(a, b);
    }

    interface MathOperation {
        int operation(int a, int b);
    }
Copy after login

5. Scope scope of Lambda expression

Within the Lambda expression expression body, you can access variables outside the expression body, but you cannot modify other variables.
Detailed explanation of Lambda expressions in Java examples

6. Reference writing method of Lambda expression

When learning Lambda, you may also find a strange way of writing, such as the following code:

// 方法引用写法GreetingService greetingService = System.out::println;
        greetingService.sayMessage("hello world");
Copy after login

A symbol that I have never seen before appears here::. This way of writing is called a method reference.
Obviously, using method references is simpler than ordinary Lambda expressions.

If the implementation of the functional interface happens to be implemented by calling a method, then we can use method references.

public class Java8Tester {


    public static void main(String args[]){

        // 静态方法引用--通过类名调用
        GreetingService greetingService = Test::MyNameStatic;
        greetingService.sayMessage("hello");
        Test t = new Test();
        //实例方法引用--通过实例调用
        GreetingService greetingService2 = t::myName;
        // 构造方法方法引用--无参数
        Supplier<test> supplier = Test::new;
        System.out.println(supplier.get());
    }



    interface GreetingService {
        void sayMessage(String message);
    }}class Test {
    // 静态方法
    public static void MyNameStatic(String name) {
        System.out.println(name);
    }

    // 实例方法
    public void myName(String name) {
        System.out.println(name);
    }

    // 无参构造方法
    public Test() {
    }}</test>
Copy after login

7、Lambda表达式的优缺点

优点:

  • 更少的代码行-lambda表达式的最大好处之一就是减少了代码量。我们知道,lambda表达式只能与功能接口一起使用。例如,Runnable 是一个接口,因此我们可以轻松地应用lambda表达式。

  • 通过将行为作为方法中的参数传递来支持顺序和并行执行-通过在Java 8中使用Stream API,将函数传递给collection方法。现在,集合的职责是以顺序或并行的方式处理元素。

  • 更高的效率-过使用Stream API和lambda表达式,可以在批量操作集合的情况下获得更高的效率(并行执行)。 此外,lambda表达式有助于实现集合的内部迭代,而不是外部迭代。

缺点

  • 运行效率-若不用并行计算,很多时候计算速度没有比传统的 for 循环快。(并行计算有时需要预热才显示出效率优势)
  • 很难调试-Lambda表达式很难打断点,对调式不友好。
  • 不容易看懂-若其他程序员没有学过 lambda 表达式,代码不容易让其他语言的程序员看懂(我学Lambda表达式的原因是看不懂同事写的Lambda表达式代码)

推荐学习:《java视频教程

The above is the detailed content of Detailed explanation of Lambda expressions in Java examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!