Introduction to Lambda Expressions-Introduction and Basic Grammar

1. What is a lambda expression?

  1. JDK1.8 began to support lambda expressions, which makes programming more elegant
  2. Use lambda to more concisely realize the declaration and invocation of anonymous inner classes and functions
  3. Provides stream processing based on lambda, which greatly simplifies the operation of collections

2. Comparison with traditional code
Insert picture description here
Insert picture description here

Three, basic grammar

(Parameter list) -> Implementation statement

Parameter list : Use commas to separate parameters, parameter types can be omitted, single parameter brackets can be omitted

Implementation statement : write directly on a single line, wrap multiple lines with {}

note:

Lambda expressions can only implement interfaces that have and only one abstract method. Java calls them "functional interfaces"

Implementation code:


public interface Lambda {
    
    
    public float operator(int a, int b);
}

public class LambdaSample {
    
    
    public static void main(String[] args) {
    
    
        // 标准写法
        Lambda addition = (a, b) -> {
    
    
            System.out.println("加法运算");
            return a + b;
        };
        System.out.println(addition.operator(3, 4));
        // 简洁写法
        Lambda subtruction = (a, b) ->
                a - b;
        System.out.println(subtruction.operator(4, 3));


    }
};

Guess you like

Origin blog.csdn.net/qq_36792120/article/details/112015724