JavaEE basics (3) Lambda expression

Introduction

Lambda expressions (also called closures) are one of the most anticipated and welcome new features in Java 8. At the level of Java syntax, Lambda expressions allow a function to be used as a method parameter (a function is passed to the method as a parameter), or to treat code as data. Lambda expressions can simplify the use of functional interfaces. A functional interface is an ordinary interface with only one abstract method. An interface like this can use Lambda expressions to simplify code writing

Prerequisites for using Lambda expressions

The corresponding interface has one and only one abstract method! ! !

Basic grammar

The basic syntax of Lambda expressions: A new operator "->" was introduced in Java 8. This operator is called the arrow operator or Lambda operator. The
arrow operator splits the Lambda expression into two parts:
Left: Lambda expression The parameter list of the formula On the
right: the function to be executed in the Lambda expression, that is, the Lambda body

(args1, args2...) -> {
    
    };

Important characteristics of lambda expressions

  • Optional type declaration: there is no need to declare the parameter type, the compiler can uniformly identify the parameter value.
  • Optional parameter parentheses: one parameter does not need to define parentheses, but multiple parameters need to define parentheses.
  • Optional curly braces: If the body contains a statement, curly braces are not required.
  • Optional return keyword: If the subject has only one expression return value, the compiler will automatically return the value. The braces need to specify that the expression returns a value.

Advantages and disadvantages of using Lambda expressions

advantage

Using Lambda expressions can simplify the use of anonymous internal classes of interfaces and reduce the generation of class files, which may be a trend in future programming.

Disadvantage

The use of Lambda expressions will weaken the readability of the code, and the use of Lambda expressions has relatively strong limitations. It can only be used when the interface has only one abstract method, and it is not suitable for debugging.

Functional interface

  • Only functional interfaces can be converted to lambda expressions
  • An interface with only one abstract method is called a functional interface!
  • A functional interface can be explicitly represented by @FunctionalInterface. When the identified interface does not meet the requirements, the compiler will prompt an error

Case

Case 1 No parameters and no return

public class Demo01 {
    
    

    public static void main(String[] args) {
    
    

        // 1.传统方式 需要new接口的实现类来完成对接口的调用
        ICar car1 = new IcarImpl();
        car1.drive();

        // 2.匿名内部类使用
        ICar car2 = new ICar() {
    
    
            @Override
            public void drive() {
    
    
                System.out.println("Drive BMW");
            }
        };
        car2.drive();

        // 3.无参无返回Lambda表达式
        ICar car3 = () -> {
    
    System.out.println("Drive Audi");};
        car3.drive();

        // 4.无参无返回且只有一行实现时可以去掉{}让Lambda更简洁
        ICar car4 = () -> System.out.println("Drive Ferrari");
        car4.drive();

        // 去查看编译后的class文件 大家可以发现 使用传统方式或匿名内部类都会生成额外的class文件,而Lambda不会
    }

}

interface ICar {
    
    

    void drive();
}

class IcarImpl implements ICar {
    
    

    @Override
    public void drive() {
    
    
        System.out.println("Drive Benz");
    }
}

Case 2 has parameters and return values

public class Demo02 {
    
    

    public static void main(String[] args) {
    
    

        // 1.有参无返回
        IEat eat1 = (String thing) -> System.out.println("eat " + thing);
        eat1.eat("apple");

        // 参数数据类型可以省略
        IEat eat2 = (thing) -> System.out.println("eat " + thing);
        eat2.eat("banana");

        // 2.多个参数
        ISpeak speak1 = (who, content) -> System.out.println(who + " talk " + content);
        speak1.talk("John", "hello word");

        // 3.返回值
        IRun run1 = () -> {
    
    
            return 10;
        };
        run1.run();

        // 4.返回值简写
        IRun run2 = () -> 10;
        run2.run();
    }

}

interface IEat {
    
    

    void eat(String thing);
}

interface ISpeak {
    
    

    void talk(String who, String content);
}

interface IRun {
    
    

    int run();
}

Case 3 final type parameters

public class Demo03 {
    
    

    public static void main(String[] args) {
    
    

        // 全写
        IAddition addition1 = (final int a, final int b) -> a + b;
        System.out.println(addition1.add(1, 2));
        // 简写
        IAddition addition2 = (a, b) -> a+b;
        System.out.println(addition2.add(2, 3));
    }

}
interface IAddition {
    
    

    int add(final int a, final int b);
}

Functional interface built into Java 8

Java8 provides a java.util.function package, which contains many functional interfaces. Let’s introduce the most basic 4 (to save space, remove the comments in the source code)

Guess you like

Origin blog.csdn.net/jinian2016/article/details/108308025
Recommended