Lambda表達式
jdk 1.8 新加入的特性,簡化了簡單接口的實現
函數式接口
函數式中只有一個待實現的方法,可以使用@FunctionalInterface
注解標注函數式接口.這個接口中只能有一個待實現的方法,但可以包含默認方法,靜態方法以及Object類中的public方法
package Note.lambda_demo;@FunctionalInterface
public interface Demo01 {void test();default void defMethod() {System.out.println("default function");}static void staticMethod() {System.out.println("static function");}@Overrideboolean equals(Object object);
}
Lambda表達式的使用
在1.8之前,如果想要使用這樣的接口,通常可以使用匿名內部類實現,
Demo01 demo01 = new Demo01() {@Overridepublic void test() {System.out.println("通過匿名內部類實現接口");}};
但現在可以更簡單的使用
Demo01 demo01 = () -> {System.out.println("demo01");
};
lambda 的標準格式:
(args) -> {};
-
沒有參數括號中留白
-
如果方法體只有一條語句,可以省略
{}
,如:Demo01 demo01 = () -> System.out.println("lll");
-
如果方法體只有一條return語句,可以簡寫,如:
Demo02 demo02 = (int s) -> s * s;// 等效于Demo02 demo02 = (int s) -> {return s * s};
-
如果方法體只返回一個新實例,可以簡寫為:
Demo04 demo04 = HashMap::new;// 等效于Demo04 demo04 = () -> new HashMap();
自帶函數接口
java.util.function 包下提供了很多內置的函數式接口,常用的有Predicate<T>
、Consumer<T>
,以及Function<T, R>
,
Predicate
用來判斷傳入的值是否符合條件
@FunctionalInterface
public interface Predicate<T> {boolean test(T t);// ...
}
示例:
// 用來找出數組中的偶數
package Note.lambda_demo;import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.function.Predicate;public class Main {public Object[] filterInteger(int[] nums, Predicate<Integer> filter) {LinkedList<Integer> result = new LinkedList<Integer>();for (int i = 0; i < nums.length; i++) {if(filter.test(nums[i])){result.add(nums[i]);}}return result.toArray();}public static void main(String[] args) {Predicate<Integer> predicate = (Integer s) -> s % 2 == 0;int [] nums = {-1, 2, 8, -9, 0, 7, -5};Main main = new Main();System.out.println(Arrays.toString(main.filterInteger(nums, predicate)));}
}//~ [2, 8, 0]
Consumer
表示輸入單個參數,返回某個值的操作
@FunctionalInterface
public interface Consumer<T> {void accept(T t);
}
Function
@FunctionalInterface
public interface Function<T, R> {R apply(T t);
}
代表一類函數,這類函數接收一個T類型的參數,返回一個R類型的結果
其他
-
lambda表達式中可以省略參數類型
-
lambda表達式中可以使用實例變量、靜態變量,以及局部變量
-
如果兩個函數式接口類似,可以簡寫,如:
package Note.lambda_demo;@FunctionalInterface public interface Demo02 {int test(int a); }// 又有一個類似的接口Demo03 package Note.lambda_demo;@FunctionalInterface public interface Demo03 {int test(int s); }
使用時,可以用
::
簡寫Demo02 demo02 = (int s) -> s * s;demo01.test(); System.out.println(demo02.test(13));Demo03 demo03 = demo02::test; System.out.println(demo03.test(10));