博客 / 詳情

返回

Java 8 中需要知道的4個函數式接口-Function、Consumer、Supplier、Predicate

前言

Java 8 中提供了許多函數式接口,包括Function、Consumer、Supplier、Predicate 等等。這 4 個接口就是本篇將要分享的內容,它們都位於 java.util.function 包下。

image-20230326234016738

為什麼需要知道這幾個函數式接口?

因為這 4 個函數式接口是 Java 8 中新增的重要接口,同時 Java 8 的 Stream 新特性,也有用到這些接口,所以學習它們可以幫助我們更好地理解 Stream 流。

也正因為這是函數式接口,所以就可以使用 Lambda 表達式來寫接口的實現邏輯。而且學習的過程中可以更好地理解函數式編程的思想。

Function 接口

説明

Function 這個單詞的意思就有「函數」的意思,就數學中的 y = f(x),接收一個 x 參數,通過函數 f 運算後,返回一個結果 y。

Function 接口包含四個方法:

  • apply(T t):這是 Function 接口的主要方法,它接收一個參數並返回一個結果。同時它也是唯一的抽象的方法,剩下的都是有默認實現的(Java 8 中接口的抽象方法支持默認實現)。
  • andThen(Function after):作用是將兩個 Function 組合。首先執行當前函數,再執行 andThen 函數,並將當前函數的結果作為參數傳遞給 andThen 函數。
  • compose(Function before):同理,將兩個 Function 組合,將先執行 compose 函數,再執行當前函數,並將 compose 函數的結果作為參數傳遞給當前函數。
  • identity(): 返回一個執行恆等轉換的函數,即返回輸入參數本身。

Function 接口通常用於將一個類型的值轉換為另一個類型的值。

apply 方法

// Function 接口的泛型,第一個參數是入參類型,第二個參數是出參類型
// Function 接口只有一個抽象方法,就是 apply(),下面利用 Lambda 表達式實現這個抽象方法並創建 Function 對象
Function<Integer, String> function = num -> "GTA" + num;
// 將5這個參數傳遞給function,得到返回結果
String result = function.apply(5);
System.out.println(result); // 打印:GTA5

andThen 和 compose 方法

// 定義兩個 Function 對象進行相關轉換操作
Function<String, String> upperCase = s -> s.toUpperCase();
Function<String, String> addPostfix = s -> s + "5";
// 鏈式調用,將 gta 這個字符串參數先傳遞 upperCase 這個函數進行操作,然後將得到的結果傳遞給 addPostfix 函數進行操作,得到返回結果
String str = upperCase.andThen(addPostfix).apply("gta");
System.out.println(str); // 打印:GTA5

identify 方法

identity 方法返回一個執行恆等轉換的函數,該函數將輸入參數原樣返回。例如:

Function<String, String> identity = Function.identity();
String result = identity.apply("hello"); // result is "hello"

Consumer 接口

説明

Consumer 這個單詞的意思就有「消費者」的意思,就把入參消費了,並不會返回結果給你。

Consumer 接口包含兩個方法:

  • accept(T t):該方法接受一個參數並執行一些操作。
  • andThen(Consumer after):同理,將兩個 Consumer 組合,先後進行消費。

accept 方法

Consumer 接口通常用於消費一個參數然後執行一些操作。例如:

// Consumer 接口,泛型參數是入參類型,接受一個參數,並不返回結果,相當於消費了這個參數
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("我輸入什麼就打印什麼"); // 打印:我輸入什麼就打印什麼

andThen 方法

組合兩個 Consumer:

Consumer<String> first = s -> System.out.println(s + 5);
Consumer<String> second = s -> System.out.println(s + 6);
// 先執行 first 這個 Consumer,接着執行 second 這個 Consumer
Consumer<String> combination = first.andThen(second);
combination.accept("GTA"); // 打印:GTA5 GTA6

Supplier 接口

Supplier 接口只定義了一個 get() 方法,該方法不接受任何參數並返回一個結果。

Supplier 這個單詞的意思就有「供應者」的意思,給我的感覺就是生產者,不用參數,直接生產一個東西給你。

Supplier 接口通常用於生成一個值。例如:

// Supplier 接口,泛型參數是出參類型,不接受參數,但是會提供結果,相當於生產了某個東西
Supplier<String> supplier = () -> "提供一個我隨便打的字符串給調用方";
String text = supplier.get();
System.out.println(text); // 打印:提供一個我隨便打的字符串給調用方

Predicate 接口

説明

Predicate 這個單詞的意思就有「預言,預測,謂語,謂詞」的意思,就是用來預測判斷的。

Predicate 接口包含四個方法:

  • test(T t):該方法接受一個參數並返回一個布爾值
  • and(Predicate other):與另一個 Predicate 進行組合,實現邏輯與操作。
  • negate():與另一個 Predicate 進行組合,實現邏輯非操作。
  • or(Predicate other):與另一個 Predicate 進行組合,實現邏輯或操作。

test 方法

Predicate 接口通常用於測試一個條件是否成立。例如:

// Predicate 接口,泛型參數是入參類型,返回布爾值
Predicate<String> predicate = s -> s.contains("god23bin");
boolean flag = predicate.test("god23bin能給你帶來收穫嗎?");
System.out.println("god23bin能給你帶來收穫嗎?" + flag); // 打印:god23bin能給你帶來收穫嗎?true

and 方法

為了便於演示,這裏準備兩個 Predicate:

Predicate<String> startsWithA = (str) -> str.startsWith("A"); // 如果傳入的字符串是A開頭,則返回 true
Predicate<String> endsWithZ = (str) -> str.endsWith("Z"); // 如果傳入的字符串是Z結尾,則返回 true

使用 and 進行組合,操作:

Predicate<String> startsWithAAndEndsWithZ = startsWithA.and(endsWithZ);
System.out.println(startsWithAAndEndsWithZ.test("ABCDEFZ")); // true
System.out.println(startsWithAAndEndsWithZ.test("BCDEFGH")); // false

negate 方法

使用 negate 進行組合,操作:

Predicate<String> notStartsWithA = startsWithA.negate();
System.out.println(notStartsWithA.test("ABCDEF")); // false
System.out.println(notStartsWithA.test("BCDEFGH")); // true

or 方法

使用 or 進行組合,操作:

Predicate<String> startsWithAOrEndsWithZ = startsWithA.or(endsWithZ);
System.out.println(startsWithAOrEndsWithZ.test("ABCDEF")); // true
System.out.println(startsWithAOrEndsWithZ.test("BCDEFGH")); // false

那這些接口有什麼應用呢?

在 Stream 流中就有應用上這些函數式接口。當然,當你有相似的需求時,你自己也可以應用上這些接口。下面説下 Stream 流中的應用。

Function 接口:例如 map 方法,map 方法就是將一個類型的值轉換為另一個類型的值。

// map 方法,將 T 類型的值轉換成 R 類型的值
// R 是返回的 Stream 流的元素類型,T 是原先 Stream 流的元素類型
<R> Stream<R> map(Function<? super T, ? extends R> mapper);

Consumer 接口:例如 forEach 方法

// forEach 方法,遍歷 Stream 流中的元素,T 類型是 Stream 流的元素類型
void forEach(Consumer<? super T> action);

Supplier 接口:例如 generate 方法

// 生成一個無限長度的 Stream 流
public static<T> Stream<T> generate(Supplier<T> s) {
    Objects.requireNonNull(s);
    return StreamSupport.stream(
        new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false);
}

Predicate 接口:例如 filter 方法,使用 Predicate 進行過濾操作。

// 過濾出 Stream 流中,判斷結果為 true 的元素
Stream<T> filter(Predicate<? super T> predicate);

最後的最後

希望各位屏幕前的靚仔靚女們給個三連!你輕輕地點了個贊,那將在我的心裏世界增添一顆明亮而耀眼的星!

咱們下期再見!

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.