java函數式接口和Lambda表達式

函數式接口:在java中有且僅有一個抽象方法的接口

Lambda表達式:Lambda 表達式(lambda expression)是一個匿名函數,Lambda表達式基於數學中的λ演算得名,直接對應於其中的lambda抽象(lambda abstraction),是一個匿名函數,即沒有函數名的函數。Lambda表達式可以表示閉包(注意和數學傳統意義上的不同)(百度百科)。Lambda表達式是Java8的新特性,Lambda允許吧函數作爲一個方法的參數(函數許作爲參數傳遞進方法)。

自定義函數式接口和使用

1.無參無返回

//定義
@FunctionalInterface  //標記在接口上,“函數式接口”是指僅僅只包含一個抽象方法的接口,如果接口中有多個抽象方法會報錯
public interface MyFunciton {
	void fun();
}

//實現
public static void main(String[] args) {
	//匿名內部類
	MyFunciton mfn = new MyFunciton() {
		@Override
		public void fun() {
			System.out.println("使用匿名內部類");
		}
	};
	//調用
	mfn.fun();
	//Lambda表達式
	MyFunciton mf = ()->System.out.println("Lambda表達式");
	mf.fun();
}

2.有參無返回

@FunctionalInterface
public interface MyFunction2 {
	void fun(String msg);
}

//實現
public static void main(String[] args) {
	MyFunction2 mf2 = (msg)->System.out.println(msg);
	mf2.fun("hello world");
}

3.有參有返回

//定義
@FunctionalInterface
public interface MyFunction3 {
	int operation(int x, int y);
}
//實現
public static void main(String[] args) {
	//加法
	MyFunction3 mfadd = (x,y)->x+y;
	int add = mfadd.operation(2, 4);
	//減法
	MyFunction3 mfsub = (x,y)->x-y;
	int sub = mfsub.operation(4, 2);
}

4.作爲方法的參數

@FunctionalInterface  
public interface MyFunciton {
	void fun();
}
public class MyClass  {
	//接口式函數作爲方法的參數
	public void sayHello(MyFunciton f) {
		f.fun();
	}
	//調用
	public static void main(String[] args) {
		new MyClass().sayHello(()->System.out.println("hello..."));
	}
}

 

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