函數式接口
1. 概念
函數式接口就是一個有且只有一個抽象方法的接口(可以有其他非抽象的方法)。函數式接口可以轉化Lambda表達式。
2. 使用
2.1 @FunctionalInterface 註解使用
@FunctionalInterface 註解,作用是檢查當前接口是否符合函數式接口的規範
@FunctionalInterface
public interface FunctionalType {
void Test();
}
2.2 自定義函數接口
- 定義:
@FunctionalInterface
public interface FunctionalType {
void test();
}
- 使用:
使用一個函數式接口作爲方法的參數
public static void useFunctionalInterface(FunctionalType ft){
ft.test();
}
在main方法中調用
//使用匿名內類完成函數式接口
useFunctionalInterface(new FunctionalType(){
@Override
public void test() {
System.out.println("匿名內部類實現");
}
});
//使用lambda表達式
useFunctionalInterface(() -> System.out.println("lambda實現"));
java 中常用函數式接口
- Supplier 生產者,返回一個指定的數據類型,只有一個get()方法
public static void print1(Supplier<String> supplier) {
System.err.println(supplier.get());
}
//在main方法中調用
print1(() -> "哈哈哈哈");
輸出的結果爲紅色的 哈哈哈哈。
- Consumer消費者,消耗一個指定類型的數據
viud accept(T t);
調用accept()完成對應關係
public static void testConsumer(String str, Consumer<String> consumer) {
consumer.accept(str);
}
//main方法中調用
testConsumer("網易遊戲真坑,騰訊遊戲也好坑", (str) -> {
System.out.println(str + ",真香!!!");
});
- Predicate 判斷調節,過濾使用
boolean test(T t);
處理T類型數據,返回boolean true 或者 false
public static boolean testNegate(String str, Predicate<String> pre) {
//negate() 取反 ==》 ! pre.test(str)
return pre.negate().test(str);
}
//main方法中調用
boolean ret = testNegate("疫情總會過去的!!!",
str -> str.length() < 5);
System.out.println(ret);
輸出結果爲 true
4. Function<T,R>類型轉換,根據你指定的類型T,轉換成對應類型R
apply()方法
//Integer 轉化成 String
public static String change(Integer i, Function<Integer, String> fun) {
return fun.apply(i);
}
//main方法中調用
String change = change(10, i -> i + "");
System.out.println(change);