概念


λ表达式 是java8引入的新特性,本质上是一个匿名方法
解决问题:匿名内部类的使用

使用条件


1.作为接口方法的实现类
2.接口中只能由一个抽象方法,可以有参数和返回值
3.接口中可以有默认方法和静态方法

格式

  1. () ->{
  2. //实现类的代码
  3. };

使用

接口:

/**
 * 随便定义的接口
 * 当前接口中,有且仅有1个方法
 * @author Administrator
 *
 */
public interface Initable {
    int meth01(int num1,int num2);
}

1.不使用lambda表达式的写法

    //最初的写法
    Initable init = new InitClass();
    init.meth01(1,2);

    //接口实例的第2种方式(匿名内部类)
    Initable init = new Initable() {
    @Override
    public int meth01(int a , int b) {
        return a + b ;
      }
    };       
    init.meth01(1,2);

2.lambda表达式—无参数方法

//无参数方法
Initable init = () ->{
      System.out.println("asdfasdfasdfasdfasdf");
};


//上述情况,方法中只有一行代码,所以可以省略大括号
Initable init = () -> System.out.println("asdfasdfasdfasdfasdf");

3.lambda表达式—有一个参数(无返回值)

//常规写法
Initable init = (e) ->{
      System.out.println("asdfasdfasdfasdfasdf");
};


//只有一个参数,括号可以省略,只有一行代码,大括号也可以省略
Initable init = e ->System.out.println("asdfasdfasdfasdfasdf");

有返回值规则同下

4.lambda表达式—多个参数(无/有返回值)

//无返回值的多参数
Initable init = (e1,e2) ->{
      System.out.println("参数1:" + e1);
      System.out.println("参数2:" + e2);
    };

//有返回值的多参数,且方法中的代码不止一行
Initable init = (e1,e2) ->{
    System.out.println("参数1:" + e1);
    System.out.println("参数2:" + e2);
    return e1 + e2;
  };    

//有返回值的多参数,方法中的代码只有return一行
Initable init = (e1,e2) -> e1 + e2;