Java8学习笔记(三)--方法引入
POJO
public class Emp { private int empno; private String ename; //其余方法略 }
方法的引入分为以下四种:
- 引入静态方法
@FunctionalInterface public interface StaticMethod { int min(int a, int b); } StaticMethod staticMethod = (a, b) -> Math.min(a,b); StaticMethod staticMethod1 = Math::min;
- 引入某个对象的实例方法
@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());
- 引用某个类型的任意对象的实例方法
@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"));
- 引用构造方法
@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;
-
一般情况下,用方法引入代替普通Lambda表达式均满足以下条件:
-
返回值类型相同
-
参数类型及个数相同
比如第1/2/4种形式。
-
-
第3种形式比较特殊,需满足以下条件:
-
返回值类型相同
-
两个参数
-
类型相同
-
岁月本长而忙者自促;天地本宽而卑者自隘;风花雪月本闲,而劳忧者自冗;天行健,君子以自强不息;地势坤,君子以厚德载物;宠辱不惊,闲看庭前花开花落;去留无意,漫随天外云卷云舒.不妄取,不妄予,不妄想,不妄求,与人方便,随遇而安