函數式編程接口
Java8的庫設計師已經幫我們定義了常用的函數式接口。這些接口都在java.util.funtion包下
函數式接口名 | 抽象方法 | 說明 |
---|---|---|
Function<T, R> | R apply(T t); | 接受T返回R |
BiFunction<T, U, R> | R apply(T t, U u); | 接受T,U,返回R |
Supplier | T get(); | 無參返回T |
Consumer < T > | void accept(T t); | 接受T無返回 |
BiConsumer <T, U> | void accept(T t, U u); | 接受T,U無返回 |
Predicate | boolean test(T t) | 接受T,返回boolean |
BiPredicate<T, U> | boolean test(T t, U u); | 接受T,U返回boolean |
- 爲了好點記憶,Function有T有R,Supplier無T有R,Consumer有T無R,Predicate有T且B.
- 當然已上列出的函數式接口是較爲常見的,如果需要三個參數過着更多參數,我們可以自定義接口來。
- 還有一些非泛型方法如下,Int Long Double 型等
方法引用
-
靜態方法的方法引用
-
非靜態方法的方法引用
-
構造函數的方法引用
public class NameUseTest {
public static void main(String[] args) {
// 靜態方法引用--通過類名調用
Consumer<String> consumerStatic = AloneTest::MyNameStatic;
consumerStatic.accept("alone---static");
//實例方法引用--通過實例調用
AloneTest alone = new AloneTest();
Consumer<String> consumer = alone::myName;
consumer.accept("alone---instance");
// 構造方法方法引用--無參數
Supplier<AloneTest> supplier = AloneTest::new;
System.out.println(supplier.get());
}
}
class AloneTest {
// 靜態方法
public static void MyNameStatic(String name) {
System.out.println(name);
}
// 實例方法
public void myName(String name) {
System.out.println(name);
}
// 無參構造方法
public AloneTest() {
}
}