Java8 Lambda expression of the new features (b)

Lambda expression syntax basis: introducing a new one operator (referred to as arrow operator or operator Lambda): "->" the operator of the expression is split into two parts: the left: Lambda expressions parameter list right: Lambda required in the operation of the functions performed

  1. 语法格式一:无参数,无返回值
                () -> System.out.println("Hello Lambda!");
  2. 语法格式二:有一个参数,无返回值(参数可不加括号)
                (x) -> System.out.println(x); 或者 x -> System.out.println(x);
  3. 语法格式三:有两个以上的参数,且Lambda体重有多条语句;有两个以上的参数,且Lambda体重有一条语句,大括号和return都可省略
                Comparator<Integer> com = (x, y) -> {
                    System.out.println("函数式接口");
                    return Integer.compare(x, y);
                };
    
                Comparator<Integer> com = (x, y) ->  Integer.compare(x, y);
  4. 语法格式四:Lambda表达式中的参数列表的类型可以不用说明,jvm编译器会通过上下文进行推断出数据类型,即“类型推断”
package lambda;

import org.junit.Test;

import java.util.Comparator;
import java.util.function.Consumer;

public class TestLambda2 {

    @Test
    public void test1() {
        Runnable r = () -> System.out.println("Hello Lambda!");
        r.run();
    }

    @Test
    public void test2() {
        Consumer c = x -> System.out.println(x);
        c.accept("清风徐来");
    }

    @Test
    public void test3() {
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
//        Comparator<Integer> com = (x, y) ->  Integer.compare(x, y);
    }

    @Test
    public void test4() {
        Integer num = operation(100, (x) -> x * x);
        System.out.println(num);
    }

    //对一个数进行运算
    public Integer operation(Integer num, MyFun mf) {
        return mf.getValue(num);
    }
}
MyFun的定义参考前一节:https://blog.csdn.net/qq_38358499/article/details/104636487
注意:lambda需要“函数式接口”的支持,
      函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解修饰:@FunctionalInterface,来检查是否是函数式接口
Published 111 original articles · won praise 57 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_38358499/article/details/104638162