This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

A few days ago when I looked at the Source code of Spring Cloud Gateway, I often saw the lamda expression. Since I am not very familiar with lamda expression, I hereby relearn it.

preface

Lambda expressions are the most important new feature released in Java 8. It allows functions to be passed as arguments to a method. Lambda expressions can make code much more compact. It is important to note that the use of LAMda expressions depends on functional interfaces.

Why use lamda expressions

So far, the biggest advantage of using LAMda expressions is that they simplify code, making it more compact.

Take the most common thread creation example:

  1. The traditional way

    public class Test {
        public static void main(String[] args) {
            Thread thread = new Thread(newRunTest()); thread.run(); }}class RunTest implements Runnable{
    ​
        @Override
        public void run(a) {
            System.out.println(123); }}Copy the code
  2. Ordinary anonymous inner class

    public class Test {
        public static void main(String[] args) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run(a) {
                    System.out.println("123"); }}); thread.run(); }}Copy the code
  3. Lamda expression method

    public class Test {
    ​
        public static void main(String[] args) {
            Thread thread = new Thread(() -> {
                System.out.println(123); }); thread.run(); }}Copy the code

By comparison, the lamda expression approach is much cleaner.

Relevant concepts

Lamda expression format

Lamda expressions generally consist of the following formats:

(parameters) -> expression
或
(parameters) ->{ statements; }
Copy the code

See the following examples

() - >5; // No argument, return 5
​
(int x,int y)->5*x+6*y; // Multiple arguments, return 5*x+6*y result
​
x->5*x // Single argument, return 5*x result. When there is only one parameter, you can ignore the parentheses and parameter types
Copy the code

Functional interface

The use of LAMda expressions depends on functional interfaces. A functional interface is any interface that contains only one abstract method.

A code example is as follows:

@FunctionalInterface
public interface TestInterface {
    int test(int x);
}
Copy the code

In order to prevent the interface from having multiple functions after a function is added to the interface, we can declare @functionalInterface above the interface class.

Lamda implements functional interfaces as follows:

public class Test {
    public static void main(String[] args) throws Exception {
        TestInterface test;
        test = x->{
            System.out.println(5*x);
            return 5*x;
        };
        int num = test.test(6); System.out.println(num); }}Copy the code

As can be seen from the above code, lamda statements that assign values to functional interfaces are essentially implementations of interface methods.

Method references

In addition to the normal lamda expression -> type, there is another way to write it, called a method reference.

A method reference is a method that assigns values to a functional interface if the parameters of a method are the same and the return value type is the same.

Method references are in the following format:

// Class name :: method name
Integer::parseInt
Copy the code

A code example is as follows:

public class Test {
    public static void main(String[] args) throws Exception {
        TestInterface testInterface;
        testInterface = Integer::parseInt;
        int test1 = testInterface.test("123");
        // The above code is equivalent to the following code
        testInterface = x -> {
            return Integer.parseInt(x);
        };
        int test2 = testInterface.test("123"); }}Copy the code

In addition, method references have the following conditions:

  • Constructor reference: its syntax is Class::new, or the more general Class< T >::new instance is as follows:

    final Car car = Car.create( Car::new ); 
    final List< Car > cars = Arrays.asList( car );
    Copy the code
  • Static method references: Its syntax is Class::static_method, as shown in the following example:

    cars.forEach( Car::collide );
    Copy the code
  • A method reference to an arbitrary object of a particular Class::method

    cars.forEach( Car::repair );
    Copy the code
  • A method reference to a specific object: its syntax is instance::method

    final Car police = Car.create( Car::new ); cars.forEach( police::follow );
    Copy the code