Java 函數語言程式設計 - 組成



函式式組成是指將多個函式組合成單個函式的技術。我們可以組合 Lambda 表示式。Java 提供內建支援,使用謂詞和函式類。以下舉例說明如何使用謂詞方法組合兩個函式。

import java.util.function.Predicate;
public class FunctionTester {
   public static void main(String[] args) {
      Predicate<String> hasName = text -> text.contains("name");
      Predicate<String> hasPassword = text -> text.contains("password");
      Predicate<String> hasBothNameAndPassword = hasName.and(hasPassword);
      String queryString = "name=test;password=test";
      System.out.println(hasBothNameAndPassword.test(queryString));
   }
}

輸出

true

謂詞提供 and() 和 or() 方法來組合函式。而 函式提供 compose 和 andThen 方法來組合函式。以下舉例說明如何使用函式方法組合兩個函式。

import java.util.function.Function;
public class FunctionTester {
   public static void main(String[] args) {
      Function<Integer, Integer> multiply = t -> t *3;
      Function<Integer, Integer> add = t -> t  + 3;
      Function<Integer, Integer> FirstMultiplyThenAdd = multiply.compose(add);
      Function<Integer, Integer> FirstAddThenMultiply = multiply.andThen(add);
      System.out.println(FirstMultiplyThenAdd.apply(3));
      System.out.println(FirstAddThenMultiply.apply(3));
   }
}

輸出

18
12
廣告
© . All rights reserved.