淺談Java中Lambda表達式的相關操作
可以對一個接口進行非常簡潔的實現。
Lambda對接口的要求?接口中定義的抽象方法有且只有一個才可以。
傳統實現一個接口需要這樣做:方法一:
// 實現接口,同時必須重寫接口中抽象方法class Test implements IntrfacefN { @Override public void getUser(int a, int b) { }}// @FunctionalInterface 注解意思:函數式接口,用來做規范,有這個注解,說明此接口有且只有一個抽象方法!!! @FunctionalInterfaceinterface IntrfacefN{ public void getUser(int a, int b);}
方法二:匿名表達式
public class Lamda { public static void main(String[] args) {// 匿名表達式實現接口IntrfacefN intrfacefN1 = new IntrfacefN(){ @Override public void getUser(int a, int b) { }}; }}
使用Lambda -> 只關注參數和方法體(返回值類型不需要寫、類型不需要寫)
public class Lamda { public static void main(String[] args) {// 實現接口,后邊匿名函數就是重寫的方法!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); }}
參數類型
IntrfacefN intrfacefN = (a, b) -> System.out.println(a-b);
小括號前提只有一個參數情況
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表達式的實現指向一個已實現的方法,這樣做相當于公共邏輯部分的抽離,實現復用。
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);}
還有更簡潔的實現:方法隸屬者:語法 - 方法隸屬者::方法名補充下:這個方法隸屬者,主要看方法是類方法還是對象方法,如果是類 - 方法類::方法名 ,如果是對象方法 - 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);}
到此這篇關于淺談Java中Lambda表達式的相關操作的文章就介紹到這了,更多相關Java Lambda表達式內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: