淺談Java中Lambda表達(dá)式的相關(guān)操作
可以對一個接口進(jìn)行非常簡潔的實現(xiàn)。
Lambda對接口的要求?接口中定義的抽象方法有且只有一個才可以。
傳統(tǒng)實現(xiàn)一個接口需要這樣做:方法一:
// 實現(xiàn)接口,同時必須重寫接口中抽象方法class Test implements IntrfacefN { @Override public void getUser(int a, int b) { }}// @FunctionalInterface 注解意思:函數(shù)式接口,用來做規(guī)范,有這個注解,說明此接口有且只有一個抽象方法!!! @FunctionalInterfaceinterface IntrfacefN{ public void getUser(int a, int b);}
方法二:匿名表達(dá)式
public class Lamda { public static void main(String[] args) {// 匿名表達(dá)式實現(xiàn)接口IntrfacefN intrfacefN1 = new IntrfacefN(){ @Override public void getUser(int a, int b) { }}; }}
使用Lambda -> 只關(guān)注參數(shù)和方法體(返回值類型不需要寫、類型不需要寫)
public class Lamda { public static void main(String[] args) {// 實現(xiàn)接口,后邊匿名函數(shù)就是重寫的方法!IntrfacefN intrfacefN = (int a, int b) -> System.out.println(a-b);intrfacefN.getUser(1, 2); }}
不定參
@FunctionalInterfaceinterface IntrfacefN{ public void getUser(int... a);}public class Lamda { public static void main(String[] args) {IntrfacefN intrfacefN = (int ...a) -> { for (int i = 0; i < a.length; i ++) {System.out.println(a[i]); }};intrfacefN.getUser(1, 2); }}
參數(shù)類型
IntrfacefN intrfacefN = (a, b) -> System.out.println(a-b);
小括號前提只有一個參數(shù)情況
IntrfacefN intrfacefN = a -> System.out.println(a);
方法大括號
方法體只有一句代碼
IntrfacefN intrfacefN = (a, b) -> System.out.println(a-b);
返回return
如果大括號中只有一條返回語句,則return 也可以省略
IntrfacefN intrfacefN = (a, b) -> { return a-b};// 省略之后寫法:IntrfacefN intrfacefN = (a, b) -> a-b;高級部分
方法的引用
將一個Lambda表達(dá)式的實現(xiàn)指向一個已實現(xiàn)的方法,這樣做相當(dāng)于公共邏輯部分的抽離,實現(xiàn)復(fù)用。
public class Lamda { public static void main(String[] args) {IntrfacefN intrfacefN = (a, b) -> add(a, b);intrfacefN.getUser(1, 2); } public static void add(int a, int b) {System.out.println(a+b); }} @FunctionalInterfaceinterface IntrfacefN{ public void getUser(int a, int b);}
還有更簡潔的實現(xiàn):方法隸屬者:語法 - 方法隸屬者::方法名補(bǔ)充下:這個方法隸屬者,主要看方法是類方法還是對象方法,如果是類 - 方法類::方法名 ,如果是對象方法 - new 方法類::方法名
public class Lamda { public static void main(String[] args) {IntrfacefN intrfacefN = Lamda::add;intrfacefN.getUser(1, 2); } public static void add(int a, int b) {System.out.println(a+b); }} @FunctionalInterfaceinterface IntrfacefN{ public void getUser(int a, int b);}
到此這篇關(guān)于淺談Java中Lambda表達(dá)式的相關(guān)操作的文章就介紹到這了,更多相關(guān)Java Lambda表達(dá)式內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用ajax跨域調(diào)用springboot框架的api傳輸文件2. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字3. Python查詢oracle數(shù)據(jù)庫速度慢的解決方案4. python 實現(xiàn)mysql自動增刪分區(qū)的方法5. vue中關(guān)于checkbox使用的問題6. Python matplotlib畫圖時圖例說明(legend)放到圖像外側(cè)詳解7. python新手學(xué)習(xí)可變和不可變對象8. PHP實現(xiàn)圖片旋轉(zhuǎn)的方法詳解9. php字符串使用詳細(xì)了解10. 通過python調(diào)用adb命令對App進(jìn)行性能測試方式
