Java Lambda表達式 簡記

>lambda表達式 :

是對函數式接口(有且只有一個需要被實現的抽象方法的接口@FunctionalInterface)的實現。

>lambda表達式的簡化(略)

>函數引用:

引用一個已經存在的方法,使其替代lambda表達式完成接口的實現。

(要求被引用方法,參數(數量、類型)和返回值,必須和接口中定義的一致)

函數引用語法:

1)靜態方法引用

類::靜態方法

2)非靜態方法引用

對象::非靜態方法

3)構造方法

類名::new

>入門實例:

@FunctionalInterface
public interface MyLambdaInterface {
	public void method(int a, int b);
}
public class TestLambda {
	public static void main(String[] args) {
		MyLambdaInterface mylambda = (a, c) -> {
			System.out.println("ac" + ":" + a + " " + c);
		};
		mylambda.method(1, 2);

		MyLambdaInterface myLambdaInterface2 = new ABC()::getsum;
		myLambdaInterface2.method(3, 4);
	}
}

class ABC {
	public void getsum(int a, int b) {
		System.out.println("引用方法ab:" + a + "  " + b);
	}
}

運行結果:

ac:1 2
引用方法ab:3  4

>應用:

Runnable接口是一個函數接口

public class Test {
	public static void main(String[] args) {
		new Thread(() -> {
			System.out.println("abc");
		}).start();
		;
		new Thread(new ABC()::run, "引用方式Thread").start();
	}
}

class ABC {
	public void run() {
		System.out.println("def");
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章