14年,Oracle公司如期發佈了Java 8正式版。現現在4年過去了,終於鼓起勇氣認真對待它,就好似雖然認識了好幾年的夥伴,忽然感受要成爲情侶的感受……
JDK 1.8 API包含了不少內建的函數式接口,在老Java中經常使用到的好比Comparator或者Runnable接口,這些接口都增長了@FunctionalInterface註解以便能用在lambda上。現現在,咱們則從Function經常使用函數入口,真正瞭解一下。php
name | type | description |
---|---|---|
Consumer | Consumer< T > | 接收T對象,不返回值 |
Predicate | Predicate< T > | 接收T對象並返回boolean |
Function | Function< T, R > | 接收T對象,返回R對象 |
Supplier | Supplier< T > | 提供T對象(例如工廠),不接收值 |
UnaryOperator | UnaryOperator | 接收T對象,返回T對象 |
BinaryOperator | BinaryOperator | 接收兩個T對象,返回T對象 |
標註爲FunctionalInterface的接口被稱爲函數式接口,該接口只能有一個自定義方法,可是能夠包括從object類繼承而來的方法。若是一個接口只有一個方法,則編譯器會認爲這就是一個函數式接口。是不是一個函數式接口,須要注意的有如下幾點:css
Function經常使用方法&&實踐java
//將Function對象應用到輸入的參數上,而後返回計算結果。
R apply(T t);
//返回一個先執行當前函數對象apply方法再執行after函數對象apply方法的函數對象。
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
//返回一個先執行before函數對象apply方法再執行當前函數對象apply方法的函數對象
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
compose 和 andThen 的不一樣之處是函數執行的順序不一樣。compose 函數先執行參數,而後執行調用者,而 andThen 先執行調用者,而後再執行參數。web
public static void main(String[] args) {
Function<Integer, Integer> name = e -> e * 2;
Function<Integer, Integer> square = e -> e * e;
int value = name.andThen(square).apply(3);
System.out.println("andThen value=" + value);
int value2 = name.compose(square).apply(3);
System.out.println("compose value2=" + value2);
//返回一個執行了apply()方法以後只會返回輸入參數的函數對象
Object identity = Function.identity().apply("huohuo");
System.out.println(identity);
}
直接看結果:app
andThen value=36 compose value2=18 huohuo
apply基本應用ide
字符串長度記錄返回svg
public class MyFunction implements Function<String,Integer>{
@Override
public Integer apply(String s) {
return s.length();
}
}
返回兩個字符串的鏈接,BiFunction與Function的不一樣就是傳入兩個參數,依舊返回一個值。函數
public class MyBiFunction implements BiFunction<String, String, String> {
@Override
public String apply(String s, String s2) {
return s+";"+s2;
}
}
最後調用結果:ui
private static String hello = "Nice to meet you";
private static String name = "my name is huohuo";
public static void main(String[] args) {
MyFunction myFunction = new MyFunction();
MyBiFunction biFunction = new MyBiFunction();
int num = myFunction.apply(hello);
String valueBi = biFunction.apply(hello, name);
//hello長度返回
System.out.println(num);
//語句整合返回
System.out.println(valueBi);
}
返回值:spa
16
Nice to meet you;my name is huohuo
其實使用的過程感受這些都無所必要,可是對於新特性以及代碼規範而言,即便是簡易代碼,也有了一個整合的過程。Function簡單實踐僅此爲止,下篇文章講述Predicate的使用。