Java8学习笔记(三)--方法引入

POJO

public class Emp {
    private int empno;
    private String ename;
    //其余方法略
}

方法的引入分为以下四种:

    1. 引入静态方法
@FunctionalInterface
    public interface StaticMethod {
        int min(int a, int b);
    }

    StaticMethod staticMethod = (a, b) -> Math.min(a,b);
    StaticMethod staticMethod1 = Math::min;
    1. 引入某个对象的实例方法
@FunctionalInterface
public interface InstanceMethodOfParticularObject {
    void setEmpName(String name);
}

    Emp emp = new Emp(1,"eName");
    
    //普通Lambda表达式
    InstanceMethodOfParticularObject instanceMethodOfParticularObject = name -> emp.setEname(name);
    instanceMethodOfParticularObject.setEmpName("haha");
    System.out.println(emp.getEname());
    
    //方法引入--引用某个对象的实例方法
    InstanceMethodOfParticularObject instanceMethodOfParticularObject1 = emp::setEname;
    instanceMethodOfParticularObject1.setEmpName("xixi");
    System.out.println(emp.getEname());
    1. 引用某个类型的任意对象的实例方法
@FunctionalInterface
public interface InstanceMethodOfArbitraryObject {
    boolean equale(String a,String b);
}

    InstanceMethodOfArbitraryObject instanceMethodOfArbitraryObject = (a, b) –> a.equals(b);
    InstanceMethodOfArbitraryObject instanceMethodOfArbitraryObject1 = String::equals;

    System.out.println(instanceMethodOfArbitraryObject1.equale("a","b"));
    System.out.println(instanceMethodOfArbitraryObject.equale("a","a"));
    1. 引用构造方法
 
@FunctionalInterface
public interface ConstructorWithFullFields {
    Emp getNewEmp(int empno,String ename);
}

    //无参构造
    ConstructorWithNoField<Emp> constructorWithNoField = ()-> new Emp();
    ConstructorWithNoField<Emp> constructorWithNoField1 = Emp::new;

    //全参构造
    ConstructorWithFullFields constructorWithFullFields = ((empno, ename) -> new Emp(empno,ename));
    ConstructorWithFullFields constructorWithFullFields1 = Emp::new;
  1. 一般情况下,用方法引入代替普通Lambda表达式均满足以下条件:

    1. 返回值类型相同

    2. 参数类型及个数相同

      比如第1/2/4种形式。

  2. 第3种形式比较特殊,需满足以下条件:

    1. 返回值类型相同

    2. 两个参数

    3. 类型相同

posted @ 2017-10-12 18:14  vvning  阅读(182)  评论(0编辑  收藏  举报