java 8 lambda 表达式

104 阅读2分钟

lambda 表达式语法

当一个接口只有一个抽象函数 可以使用lambda表达式来创建这个接口的对象

lambda表达式:(方法参数列表) -> {方法体}

1、当可以推导出参数的类型则可以省略参数类型

BiFunction<String,String,Integer> function = (x,y) -> x.length() + y.length();

2、当方法体只有一行代码时可以省略{} 3、当只有一个参数时可以省略参数的()

Function<String,Integer> function = e -> e.length();

4、对于没有参数的方法不能省略()

Supplier<List>  function = () -> new ArrayList();

5、方法体中需要多行代码,{}不能省略,有返回值 return也不能省略

方法引用

方法的4中方式

类::静态方法

类::实例方法

对象::实列方法

类::new

1、类::静态方法 静态函数参数的列表必须要和函数接口的方法的参数列表一样

public class LambdaDemo {

    public static List<Integer> createList(){
        return new ArrayList<>();
    }

    public static List<Integer> createList(int capacity){
        return new ArrayList<>(capacity);
    }

    public static void main(String[] args) {
        Supplier<List>  function = LambdaDemo::createList;
        //会调用对应的有参数的createList方法,当调用function1对象的 R apply(T t) 方法时
        //传入的参数会当做 createList(int capacity)方法的参数传入
        //因此,引用的方法的参数列表必须要和函数接口的方法参数列表一样
        Function<Integer,List> function1 = LambdaDemo::createList;
    }
}

2、类::实例方法 函数接口的方法至少要有一个参数,第一个参数是表达式(类::实例方法)"类" 的实例

public class LambdaDemo1 {

    public List<Integer> createList(){
       return new ArrayList<Integer>();
    }

    public static void main(String[] args) {
        // LambdaDemo1 的实列被当作参数传给函数接口的方法apply(T t)
        Function<LambdaDemo1,List> function = LambdaDemo1::createList;
        LambdaDemo1 lambdaDemo1 = new LambdaDemo1();
        List list = function.apply(lambdaDemo1);

        //apply(T t, U u)第一个参数对象是函数(函数引用部分的函数compareTo)的调用者,第二个参数是第一个参数调用的方法的参数
        //当有多个参数时依次类推,第一个参数是函数的调用者,后边的参数是被调用的函数的参数
        BiFunction<String,String,Integer> function1 = String::compareTo;
    }
}

3、对象::实例方法 用法基本和类::静态方法相同。对象的方法参数列表要和函数接口的方法参数列表一致

public class LambdaDemo2 {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        BiConsumer<String,Integer>  function = map::put;
    }
}

4:类::new 构造函数的参数列表要与对应的函数接口的方法参数列表一致

class Person{
    private String name;
    private Date birthday;
    private int gender;

    public Person(String name, Date birthday, int gender) {
        this.name = name;
        this.birthday = birthday;
        this.gender = gender;
    }
    public Person(String name) {
        this.name = name;
        this.gender = gender;
    }
    public Person() {}
}

interface Fun<A,B,C,D>{
    D apply(A a,B b,C c);
}

public class LambdaDemo3 {
    public static void main(String[] args) {
        Supplier<Person> function = Person::new;
        Function<String,Person> function1 = Person::new;
        Fun<String,Date,Integer,Person> fun = Person::new;
    }
}