生活随笔
收集整理的這篇文章主要介紹了
Java8学习笔记(三)--方法引入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
POJO
public class Emp {private int empno;private String ename;//其余方法略
}
方法的引入分為以下四種:
引入靜態方法 @FunctionalInterfacepublic 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種形式比較特殊,需滿足以下條件:
返回值類型相同
兩個參數
類型相同
轉載于:https://www.cnblogs.com/vvning/p/7657487.html
總結
以上是生活随笔為你收集整理的Java8学习笔记(三)--方法引入的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。