[Detailed explanation of Java lambda expression]

In Java programming, we often encounter situations where we need to implement an interface or inherit a class. However, sometimes we don't need a complete class to implement this interface, but only a simple function. At this time, we can use Lambda expressions introduced in Java 8. This article will introduce the basic concepts and advantages of Lambda expressions and analyze their simplicity through specific examples.

Table of contents

1 Introduction

2. Advantages of Lambda expressions

1.Simple

2. Easy to parallelize calculations

3. Improve code readability

Lambda expressions can make code easier to understand, especially for those new to functional programming.

3. Derivation

Summarize


1 Introduction

Let’s talk about the name Lambda first, Lambda is not an abbreviation, it is the pronunciation of the eleventh letter of the Greek alphabetλ,Lambda expression is a concise way to express anonymous functions, which allows us to pass functions as parameters to other methods or as returns.

2.Advantages of Lambda expressions

1.Simple

Lambda expressions allow us to express functional interfaces (interfaces with one and only one abstract method) in a concise way. This allows us to define a simple method in one line of code without writing a complete class, so the code is cleaner and cleaner.

2.Easy to parallel computing

Lambda expressions can be used with the Stream API introduced in Java 8 to allow easy parallel processing of collections. By splitting the data into multiple parts and performing operations on different threads, we can take full advantage of the performance of multi-core processors.

import java.util.Arrays;
import java.util.List;

public class ParallelComputingExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        int sumOfSquares = numbers.parallelStream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .sum();

        System.out.println("Sum of squares of even numbers: " + sumOfSquares);
    }
}
 
 

In this example, we first create a list of integers from 1 to 10. Then, we create a parallel stream using the parallelStream() method. Next, we filter out the even numbers using the filter() method, and then calculate the square of each even number using the map() method. Finally, we calculate the sum of all squares using the sum() method.

3. Improve code readability
Lambda expressions can make code easier to understand, especially for those new to functional programming.

3. Derivation

Next, we will experience the simplicity of lambda expressions in this order.

 

 First create an interface

interface lambda{
    void test();
}

 Create an external class to implement the interface

class demo1 implements lambda{
    @Override
   public  void test(){
        System.out.println("hello lambda!!!");
    }
}

Call interface

public class Main {
    public static void main(String[] args) {
       lambda test = new demo1();
       test.test();

    }

}

It is a bit troublesome to write the implementation class outside. We optimize the code and use static inner classes to implement the interface.

public class Main {

   public static class demo1 implements lambda{
        @Override
        public  void test(){
            System.out.println("hello lambda!!!");
        }
    }

    public static void main(String[] args) {
       lambda test = new demo1();
       test.test();

    }

}
interface lambda{
    public void test();
}

The running results are also correct. Next, we will further optimize and use local internal classes.

public class Main {
    
    public static void main(String[] args) {
        class demo1 implements lambda {
            @Override
            public void test() {
                System.out.println("hello lambda!!!");
            }
        }

        lambda test = new demo1();
        test.test();

    }

}
interface lambda {
    public void test();
}

The code can be further optimized. This time we don’t even need a class name and use anonymous inner classes directly.

public class Main {

    public static void main(String[] args) {
        lambda test = new lambda() {
            @Override
            public void test() {
                System.out.println("hello lambda!!!");
            }
        };
        test.test();

    }

}
interface lambda {
    public void test();
}

The implementation class no longer has a name, can it still be optimized? The Lambda expression introduced in Java 8 can continue to be optimized, and the interface name and method name are simply thrown away (it is so willful)

public class Main {

    public static void main(String[] args) {
        lambda test = ()->{
                System.out.println("hello lambda!!!");
            };
        test.test();

    }

}
interface lambda {
    public void test();
}

Is the code much simpler? Just use ()-> instead of the interface name and method name; in fact, the code can be further optimized.

If there is only one statement in the method, the curly braces are not required.

  lambda test = ()->
                System.out.println("hello lambda!!!");
        test.test();

Lambda expressions can pass parameters. If there is only one parameter, the parentheses are not required.

public class Main {

    public static void main(String[] args) {

        lambda test = a->
                System.out.println("hello lambda!!!");
        test.test(520);

    }

}
interface lambda {
    public void test(int a);
}

As you can see, after using Lambda expressions, our code becomes more concise and clear, and it is also easier to read and maintain.

Summarize

 This article introduces Lambda expressions in Java 8, including its basic concepts, advantages, and analysis of its simplicity through specific examples. By using Lambda expressions, we can simplify code, improve code readability, and facilitate parallel processing. I hope this article can help you better understand and use Lambda expressions in Java.

Guess you like

Origin blog.csdn.net/weixin_55939638/article/details/134562516