介绍

1、λ 希腊字母表中排序第十一位的字母,英语名称为 Lamda
2、避免匿名内部类定义过多
3、可以让你的代码看起来很简洁
4、去掉了一堆没有意义的代码,留下核心的逻辑
3、其实质属于函数式编程的概念

(params)-> expression[表达式]`
(params) -> statement[语句]`
(params) -> {statements}

推导lamda表达式

//推导Lamda表达式(实质:基于函数式编程)

public class Lamda {
    //3.静态内部类
    static class Father2 implements People{
        @Override
        public void relation() {
            System.out.println("第二阶段");
        }
    }


    public static void main(String[] args) {
        //推导第一步
        People father = new Father();
        father.relation();
        
		//推导第二步
        father = new Father2();
        father.relation();

        //4.局部内部类
        class Father3 implements People{
            @Override
            public void relation() {
                System.out.println("第三阶段");
            }
        }
        //推导第三步
        father = new Father3();
        father.relation();

        //5.匿名内部类,无类的名称,必须借助接口或者父类
        father = new People() {
            @Override
            public void relation() {
                System.out.println("第四阶段");
            }
        };
        //推导第四步
        father.relation();

        //6.使用lamda简化
        father = ()-> {
            System.out.println("第五阶段");//一条代码语句的情况下此{}可省略
        };
        //推导第五步
        father.relation();
    }
}
//1.定义一个函数式接口
interface People{
    void relation();
}

//2.实现类
class Father implements People{
    @Override
    public void relation() {
        System.out.println("第一阶段");
    }
}

例子

public class Lamda02 {
    public static void main(String[] args) {
        People02 father = null;
        father = (String name)-> System.out.println(name+"我是你爸爸");
        father.relation("小明");
    }
}

interface People02{
    void relation(String name);
}

​ 多个参数

public class Lamda02 {
    public static void main(String[] args) {
        People02 father = null;
        //多个参数也可以去掉参数类型,要么一块去掉,要么全部加上
        father = (name,age)-> System.out.println(name+"我是你爸爸"+"\n"+age+"岁");
        father.relation("小明",12);
    }
}

interface People02{
    void relation(String name,int age);//多个参数
}

​ 对比:

public class Lamda02 {
    public static void main(String[] args) {
        Father02 father02 = new Father02();
        father02.relation("小明");
    }
}

interface People02{
    void relation(String name);
}

class Father02 implements People02{
    @Override
    public void relation(String name) {
        System.out.println(name+"我是你爸爸");
    }
}

总结

  1. lamda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹。

    一行

     father = (String name)-> System.out.println(name+"我是你爸爸");
    

    多行

     father = (String name)-> {
     		System.out.println(name+"我是你爸爸");
     		System.out.println("ohhhhhhhhh");
     }
    
  2. 前提,接口是函数式的接口。

  3. 多个参数也可以去掉参数类型,要么一块去掉,要么全部加上。