Lambda表达式

  语义本身就代表了做事情的动作,没有对象的概念在其中。

  Java中使用Lambda表达式的前提:必须有 函数式接口。

  概念:有且只有一个的抽象方法的接口就叫函数式接口。

  为确保当前接口为函数式接口,在定义接口的前一行加 @FunctionalInterface

  格式:

@FunctionalInterface
public interface 函数式接口名{
    //Code...
}

  Lambda表达式使用必须要有函数式接口的推断环境。

    1、要么通过方法的参数类型类确定是那个函数式接口。

    2、要么通过复制操作来确定是那个函数式接口。

  Lambda的格式就是将抽象方法分解成为以下三点:

    1、参数  

    2、箭头  

    3、代码

  例:

public sbstract int sum(int a,int b);
//Lambda的标准格式:
(int a,int b) -> {return a+b;}
//Lambda的简化格式:
(a,b) -> a+b
//若参数有且只有一个参数,可以省略小括号。

实例:

@FunctionalInterface
public interface Calculator{
    public sbstract int sum(int a,int b);//int sum(int a,int b);
}

public class CalculatorImpl implements Calculator{
    public int sum(int a,int b){
        return a+b;
    }
}

public static void main(String[] args){
    Calculator calculator=new CalculatorImpl();
    method(calculator);
    //等于
    method((a,b) -> a+b);
}

public static void method(Calculator calculator){
    int result=calculator.sum(1,2);
    System.out.println(result);
}
View Code

相关文章:

  • 2021-08-07
  • 2021-11-23
  • 2021-10-16
  • 2021-06-04
  • 2021-08-31
  • 2021-11-13
  • 2021-08-04
  • 2021-12-23
猜你喜欢
  • 2021-12-12
  • 2021-07-02
  • 2021-09-27
  • 2021-06-11
  • 2021-07-14
  • 2021-07-10
  • 2021-12-22
相关资源
相似解决方案