一、簡述
Funciton、Consumer、Predicate是Java8中的新特性。他們都是函數式接口,位於java.util包中。
關於函數式接口,其外部特征是類上使用@FunctionalInterface注解。它有以下特點:
- 只能注解到有且僅有一個抽象方法的類上。
- 接口顯示聲明或覆蓋了java.lang.Object類中方法的方法也不算做抽象方法。
- Java8接口中static方法與default方法不算抽象方法。
他們各自的使用場景如下:
- Function
需要執行目標方法后得到返回值。
接口修飾:
@FunctionalInterface
public interface Function<T, R>{}
該類需要設置兩個泛型,T為入參類型,R為返回值類型。
主要方法:
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
- Consumer
僅需要執行目標方法,不需要得到返回值。
接口修飾:
@FunctionalInterface
public interface Consumer<T>{}
該類需要設置一個泛型,T為參數類型。
主要方法:
/**
* 對給定的參數執行此操作。
*
* @param t 入參
*/
void accept(T t);
- Predicate
經過比較,得到比較邏輯執行過后的結果,其返回類型為true、false。
接口修飾:
@FunctionalInterface
public interface Predicate<T>{}
該類需要設置一個泛型,T為參數類型。
主要方法:
/**
* 根據給定參數比較
*
* @param t 入參
* @return {@code true} 滿足條件返回true,
* otherwise {@code false}
*/
boolean test(T t);
二、實例
1、輸入數字3,得到輸入值加100的結果並轉為字符創,並返回。
# 定義函數執行方法
Function<Integer, String> func = o -> {return String.valueOf((o + 100));};
# 傳入3,執行方法,獲取返回結果
String result = func.apply(3);
System.out.println("result : " + result);
結果:
2、輸入字符“hello”,拼接字符串“ word”並輸出。
Consumer<String> consumer = o -> {System.out.println(o + " world");};
consumer.accept("hello");
結果:
3、輸入字符串“hello”,判斷長度是否等於5。
Predicate<String> predicate = o -> {return o.length() == 5;};
boolean test = predicate.test("hello");
System.out.println("result : " + test);
結果: