1.1 Java8的概述
- Java8于2014年3月發布,該版本是 Java 語言的一個重要版本,自Java5以來最具革命性的版本,該版本包含語言、編譯器、庫、工具和JVM等方面的多個新特性,
1.2 函式式介面
- 函式式介面主要指只包含一個抽象方法的介面,如:java.lang.Runnable等,
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface {@code Runnable} is used
* to create a thread, starting the thread causes the object's
* {@code run} method to be called in that separately executing
* thread.
* <p>
* The general contract of the method {@code run} is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
- Java8中提供@FunctionalInterface注解來定義函式式介面,若定義的介面不符合函式式的規范便會報錯,
/**
* 自定義函式式介面
*/
@FunctionalInterface
public interface MyFunctionInterface {
/**
* 自定義有且只有一個的抽象方法
*/
void show();
}
- Java8中增加了java.util.function包,該包包含了常用的函式式介面,具體如下:
| 介面名稱 | 方法宣告 | 功能介紹 |
|---|---|---|
| Consumer |
void accept(T t) | 根據指定的引數執行操作 |
| Supplier |
T get() | 得到一個回傳值 |
| Function<T,R> | R apply(T t) | 根據指定的引數執行操作并回傳 |
| Predicate |
boolean test(T t) | 判斷指定的引數是否滿足條件 |
1.3 函式式介面的使用方式
1.3.1 自定義類實作函式式介面得到介面型別的參考
/**
* 自定義類實作介面
*/
public class MyFunctionInterfaceImpl implements MyFunctionInterface {
@Override
public void show() {
System.out.println("這里是介面的實作類");
}
}
MyFunctionInterface myFunctionInterface = new MyFunctionInterfaceImpl();
myFunctionInterface.show();
1.3.2 使用匿名內部類的方式得到介面型別的參考
MyFunctionInterface myFunctionInterface = new MyFunctionInterface() {
@Override
public void show() {
System.out.println("匿名內部類的方式");
}
};
myFunctionInterface.show();
1.3.3 使用Lambda運算式得到介面型別的參考
- Lambda 運算式是實體化函式式介面的新方式,允許將函式當做引數進行傳遞,從而使代碼變的更加簡潔和緊湊,
- 語法格式:(引數串列) -> { 方法體; }
- 其中()、引數型別、{} 以及return關鍵字 可以省略,
MyFunctionInterface myFunctionInterface = () -> {
System.out.println("lambda運算式的方式");
};
myFunctionInterface.show();
// 省略{}后的寫法
MyFunctionInterface myFunctionInterface = () -> System.out.println("lambda運算式的方式");
myFunctionInterface.show();
更多精彩歡迎關注微信公眾號《格子衫007》!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/535970.html
標籤:Java
