Java 中的 BiFunction 介面
- 
          
            Java 中的 BiFunction apply()方法示例
- 
          
            Java 中的 BiFunction andThen()方法
- 
          
            在 BiFunction 介面中避免 NullPointerException
- 在 Java 中使用 HashMap 的 BiFunction
- BiFunction 和方法參考
- まとめ
 
在本教程中,我們將討論 Java 中的 BiFunction 介面。
BiFunction 介面是 Java 8 中引入的內建函式式介面,位於 java.util.function 包中。與接受兩個泛型(一個引數型別和一個返回型別)的 Function 介面不同,BiFunction 接受兩個引數併產生一個結果。
我們可以分配一個 lambda 表示式或一個方法引用,它接受兩個引數並將結果返回給 BiFunction 型別的物件。
BiFunction 採用三個泛型 - T、U 和 R。T 和 U 分別是第一個和第二個引數的型別。R 是函式結果的型別。
interface BiFunction<T, U, R>
BiFunction 介面有兩個方法:
- apply():它對引數執行定義的操作並返回結果。這個方法的語法是:
R apply(T t, U u) // R is the return type. T and U are the types of the two arguments
- andThen():它返回組合函式的結果。簡單來說,它首先在兩個引數上執行 BiFunction 併產生一個結果。接下來,它將結果傳遞給函式。這個方法的語法是:
default<V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after)
Java 中的 BiFunction apply() 方法示例
讓我們建立一個簡單的 BiFunction,它接受 Integer 和 Double 型別的引數並返回一個 String。我們使用 apply() 方法來傳遞引數並獲得結果。
請參見下面的示例。
import java.util.function.*;
public class SimpleTesting {
  public static void main(String args[]) {
    // BiFunction with arguments of type Integer and Double
    // and return type of String
    BiFunction<Integer, Double, String> biFunction = (a, b) -> {
      double result = a * b;
      String s = "The result from the BiFunction is: " + result;
      return s;
    };
    String output = biFunction.apply(10, 15.5);
    System.out.print(output);
  }
}
輸出:
The result from the BiFunction is: 155.0
Java 中的 BiFunction andThen() 方法
讓我們將上面定義的 BiFunction 的結果傳遞給一個函式。我們將使用 andThen() 方法。此方法首先評估 BiFunction 的結果,然後將該結果傳遞給 after 函式。
import java.util.function.*;
public class SimpleTesting {
  public static void main(String args[]) {
    // BiFunction with arguments of type Integer and Double
    // and return type of String
    BiFunction<Integer, Double, String> biFunction = (a, b) -> {
      double result = a * b;
      String s = "The result from the BiFunction is: " + result;
      return s;
    };
    // Function with argument of type String
    // and return type of Integer
    Function<String, Integer> after = s -> {
      Integer length = s.length();
      return length;
    };
    int output = biFunction.andThen(after).apply(
        10, 15.5); // first evaluates the BiFunction and then the Function
    System.out.print(output);
  }
}
輸出:
40
在 BiFunction 介面中避免 NullPointerException
如果我們將空引用傳遞給 andThen() 方法,程式碼將返回 NullPointerException。請參見下面的示例。我們應該避免此類錯誤,並始終將程式碼放在 try...catch 塊中。
import java.util.function.*;
public class SimpleTesting {
  public static void main(String args[]) {
    BiFunction<Integer, Double, String> biFunction = (a, b) -> {
      double result = a * b;
      String s = "The result from the BiFunction is: " + result;
      return s;
    };
    Function<String, Integer> after = null;
    int output = biFunction.andThen(after).apply(10, 15.5);
    System.out.print(output);
  }
}
輸出:
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:222)
	at java.base/java.util.function.BiFunction.andThen(BiFunction.java:69)
	at SimpleTesting.main(SimpleTesting.java:15)
請注意,我們不能使用 andThen() 方法整合兩個 BiFunction。
在 Java 中使用 HashMap 的 BiFunction
BiFunctions 在一些 HashMap 方法中用作引數,例如 compute()、computeIfPresent()、merge() 和 replaceAll()。
讓我們建立一個在 HashMap 中使用 BiFunction 的示例。考慮一個儲存學生卷號及其分數的 HashMap。我們需要在每個學生的分數上加上 5,除了卷號 101。
import java.util.HashMap;
import java.util.function.*;
public class SimpleTesting {
  public static void main(String args[]) {
    HashMap<Integer, Double> scoreMap = new HashMap<>();
    scoreMap.put(101, 95.2);
    scoreMap.put(102, 86.0);
    scoreMap.put(103, 91.9);
    scoreMap.put(104, 72.8);
    scoreMap.put(105, 89.5);
    System.out.println("Intial HashMap: " + scoreMap);
    // BiFunction with arguments of type Integer and Double
    // and return type of Double
    BiFunction<Integer, Double, Double> biFunction = (key, value) -> {
      if (key == 101)
        return value;
      else
        return value + 5;
    };
    scoreMap.replaceAll(biFunction);
    System.out.print("HashMap After The Update: " + scoreMap);
  }
}
輸出:
Intial HashMap: {101=95.2, 102=86.0, 103=91.9, 104=72.8, 105=89.5}
HashMap After The Update: {101=95.2, 102=91.0, 103=96.9, 104=77.8, 105=94.5}
BiFunction 和方法參考
到目前為止,我們已經使用 BiFunction 介面作為 lambda 表示式的參考。也可以使用 BiFunction 引用方法。該方法必須只接受兩個引數並返回一個結果。
讓我們編寫一個簡單的靜態方法來檢查兩個給定整數的和是否為偶數。我們可以將此方法引用分配給 BiFunction。請參見下面的示例。
import java.util.function.*;
public class SimpleTesting {
  static boolean isSumEven(int a, int b) {
    int sum = a + b;
    if (sum % 2 == 0)
      return true;
    else
      return false;
  }
  public static void main(String args[]) {
    BiFunction<Integer, Integer, Boolean> biFunction = SimpleTesting::isSumEven;
    System.out.println("Is sum of 10 and 21 even? " + biFunction.apply(10, 21));
    System.out.print("Is sum of 5 and 7 even? " + biFunction.apply(5, 7));
  }
}
輸出:
Is sum of 10 and 21 even? false
Is sum of 5 and 7 even? true
まとめ
Java BiFunction 介面是一個函式式介面。它用作 lambda 表示式或方法引用的賦值目標。當我們需要傳遞兩個引數時,BiFunction 介面優於 Function 介面。
BiFunction 介面包含兩個方法:apply() 和 andThen()。apply() 方法將函式應用於兩個給定的引數。andThen() 方法用於將 BiFunction 的結果傳遞給 Function 介面。
相關文章 - Java Stream
- Java 中的 Stream 的 reduce 操作
- Java 中的流過濾器
- Java 中的 findFirst 流方法
- 在 Java 中將 Stream 元素轉換為對映
- Java 中的 flatMap
- 在 Java 中把陣列轉換為流