Java 之 常用函數式接口


  JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景,它們主要在 java.util.function 包中被提供。
下面是最簡單的幾個接口及使用示例。

一、Supplier 接口

  java.util.function.Supplier<T> 接口僅包含一個無參的方法: T get() 用來獲取一個泛型參數指定類型的對象數據。

  由於這是一個函數式接口,這也就意味着對應的Lambda表達式需要對外提供一個符合泛型類型的對象數據。(生產接口) 

  Demo:

 1  import java.util.function.Supplier;  2 
 3     public class Demo08Supplier {  4         private static String getString(Supplier<String> function) {  5             return function.get();  6  }  7 
 8         public static void main(String[] args) {  9             String msgA = "Hello"; 10             String msgB = "World"; 11             System.out.println(getString(() ‐ > msgA + msgB)); 12  } 13     }

 

  案例:求數組元素最大值

  題目:使用 Supplier 接口作為方法參數類型,通過Lambda表達式求出int數組中的最大值。

  提示:接口的泛型請使用 java.lang.Integer

    代碼實現:

 1 public class DemoTest {  2         //定一個方法,方法的參數傳遞Supplier,泛型使用Integer
 3         public static int getMax(Supplier<Integer> sup){  4             return sup.get();  5  }  6         public static void main(String[] args) {  7             int arr[] = {2,3,4,52,333,23};  8             //調用getMax方法,參數傳遞Lambda
 9             int maxNum = getMax(()‐>{ 10                 //計算數組的最大值
11             int max = arr[0]; 12             for(int i : arr){ 13                 if(i>max){ 14                     max = i; 15  } 16  } 17             return max; 18  }); 19  System.out.println(maxNum); 20  } 21     }

 

二、Consumer 接口

     java.util.function.Consumer<T> 接口則正好與Supplier接口相反,它不是生產一個數據,而是消費一個數據,其數據類型由泛型決定。

  (1)抽象方法:accept

   Consumer 接口中包含抽象方法 void accept(T t) ,意為消費一個指定泛型的數據。基本使用如:

 1 import java.util.function.Consumer;  2 
 3     public class DemoConsumer {  4         private static void consumeString(Consumer<String> function) {  5             function.accept("Hello");  6  }  7 
 8         public static void main(String[] args) {  9             consumeString(s ‐ > System.out.println(s)); 10  } 11     }

 

  (2)默認方法:andThen
  如果一個方法的參數和返回值全都是 Consumer 類型,那么就可以實現效果:消費數據的時候,首先做一個操作,然后再做一個操作,實現組合。而這個方法就是 Consumer 接口中的default方法 andThen 。下面是JDK的源代碼:

1 default Consumer<T> andThen(Consumer<? super T> after) { 2  Objects.requireNonNull(after); 3     return (T t) ‐> { accept(t); after.accept(t); }; 4 }

 

  要想實現組合,需要兩個或多個Lambda表達式即可,而 andThen 的語義正是一步接一步操作。例如兩個步驟組合的情況:

 1 import java.util.function.Consumer;  2 
 3     public class Demo10ConsumerAndThen {  4         private static void consumeString(Consumer<String> one, Consumer<String> two) {  5             one.andThen(two).accept("Hello");  6  }  7 
 8         public static void main(String[] args) {  9  consumeString( 10                     s ‐ > System.out.println(s.toUpperCase()), 11                     s ‐>System.out.println(s.toLowerCase())); 12  } 13     }

  運行結果將會首先打印完全大寫的HELLO,然后打印完全小寫的hello。當然,通過鏈式寫法可以實現更多步驟的組合。 

  案例:格式化打印信息
  題目:下面的字符串數組當中存有多條信息,請按照格式姓名:XX。性別:XX的格式將信息打印出來。要求將打印姓名的動作作為第一個 Consumer 接口的Lambda實例,將打印性別的動作作為第二個 Consumer 接口的Lambda
例,將兩個 Consumer 接口按照順序拼接到一起。

   代碼實現:

 1 import java.util.function.Consumer;  2     public class DemoConsumer {  3         public static void main(String[] args) {  4             String[] array = { "迪麗熱巴,女", "古力娜扎,女", "馬爾扎哈,男" };  5             printInfo(s ‐> System.out.print("姓名:" + s.split(",")[0]),  6                     s ‐> System.out.println("。性別:" + s.split(",")[1] + "。"),  7  array);  8  }  9         private static void printInfo(Consumer<String> one, Consumer<String> two, String[] array) { 10             for (String info : array) { 11                 one.andThen(two).accept(info); // 姓名:迪麗熱巴。性別:女。
12  } 13  } 14     }

 

 

三、Predicate 接口

  有時候我們需要對某種類型的數據進行判斷,從而得到一個boolean值結果。這時可以使用java.util.function.Predicate<T> 接口。

  (1)抽象方法:test

    Predicate 接口中包含一個抽象方法: boolean test(T t) 。用於條件判斷的場景:
    Demo :

 1 import java.util.function.Predicate;  2 
 3     public class DemoPredicateTest {  4         private static void method(Predicate<String> predicate) {  5             boolean veryLong = predicate.test("HelloWorld");  6             System.out.println("字符串很長嗎:" + veryLong);  7  }  8 
 9         public static void main(String[] args) { 10             method(s ‐ > s.length() > 5); 11  } 12     }

 

    條件判斷的標准是傳入的Lambda表達式邏輯,只要字符串長度大於5則認為很長。

  (2)默認方法:and

    既然是條件判斷,就會存在與、或、非三種常見的邏輯關系。其中將兩個 Predicate 條件使用邏輯連接起來實現並且的效果時,可以使用default方法 and 。其JDK源碼為:

1 default Predicate<T> and(Predicate<? super T> other) { 2  Objects.requireNonNull(other); 3      return (t) ‐> test(t) && other.test(t); 4 }

 

    如果要判斷一個字符串既要包含大寫“H”,又要包含大寫“W”,那么:

 1 import java.util.function.Predicate;  2 
 3     public class Demo16PredicateAnd {  4         private static void method(Predicate<String> one, Predicate<String> two) {  5             boolean isValid = one.and(two).test("Helloworld");  6             System.out.println("字符串符合要求嗎:" + isValid);  7  }  8 
 9         public static void main(String[] args) { 10             method(s ‐ > s.contains("H"), s ‐>s.contains("W")); 11  } 12     }

 

  (3)默認方法:or

    and 類似,默認方法 or 實現邏輯關系中的JDK源碼為:

1 default Predicate<T> or(Predicate<? super T> other) { 2  Objects.requireNonNull(other); 3     return (t) ‐> test(t) || other.test(t); 4 }

 

     如果希望實現邏輯字符串包含大寫H或者包含大寫W”,那么代碼只需要將“and”修改為“or”名稱即可,其他都不變:

 1 import java.util.function.Predicate;  2 
 3     public class Demo16PredicateAnd {  4         private static void method(Predicate<String> one, Predicate<String> two) {  5             boolean isValid = one.or(two).test("Helloworld");  6             System.out.println("字符串符合要求嗎:" + isValid);  7  }  8 
 9         public static void main(String[] args) { 10             method(s ‐ > s.contains("H"), s ‐>s.contains("W")); 11  } 12     }

 

  (4)默認方法:negate

     取“非”是 negate方法,JDK源代碼為:

1 default Predicate<T> negate() { 2     return (t) ‐> !test(t); 3 }

  從實現中很容易看出,它是執行了test方法之后,對結果boolean值進行“!”取反而已。一定要在 test 方法調用之前調用 negate 方法,正如 and or 方法一樣:

 1 import java.util.function.Predicate;  2 
 3     public class Demo17PredicateNegate {  4         private static void method(Predicate<String> predicate) {  5             boolean veryLong = predicate.negate().test("HelloWorld");  6             System.out.println("字符串很長嗎:" + veryLong);  7  }  8 
 9         public static void main(String[] args) { 10             method(s ‐ > s.length() < 5); 11  } 12     }

 

  (5)案例:集合信息篩選

      題目數組當中有多條姓名+性別的信息如下,請通過 Predicate 接口的拼裝將符合要求的字符串篩選到集合ArrayList 中,需要同時滿足兩個條件

        ① 必須為女生;② 姓名為4個字

    代碼實現:

 1     import java.util.ArrayList;  2     import java.util.List;  3     import java.util.function.Predicate;  4 
 5     public class DemoPredicate {  6         public static void main(String[] args) {  7             String[] array = {"迪麗熱巴,女", "古力娜扎,女", "馬爾扎哈,男", "趙麗穎,女"};  8             List<String> list = filter(array,  9                     s ‐> "女".equals(s.split(",")[1]), 10                  s ‐>s.split(",")[0].length() == 4); 11  System.out.println(list); 12  } 13 
14         private static List<String> filter(String[] array, Predicate<String> one, 15                                            Predicate<String> two) { 16             List<String> list = new ArrayList<>(); 17             for (String info : array) { 18                 if (one.and(two).test(info)) { 19  list.add(info); 20  } 21  } 22             return list; 23  } 24     }

 

四、Function 接口

  java.util.function.Function<T,R> 接口用來根據一個類型的數據得到另一個類型的數據,前者稱為前置條件,后者稱為后置條件。

  (1)抽象方法:apply

    Function 接口中最主要的抽象方法為: R apply(T t) ,根據類型T的參數獲取類型R的結果。

      使用的場景例如:將 String 類型轉換為 Integer 類型。

 1 import java.util.function.Function;  2 
 3     public class Demo11FunctionApply {  4         private static void method(Function<String, Integer> function) {  5             int num = function.apply("10");  6             System.out.println(num + 20);  7  }  8 
 9         public static void main(String[] args) { 10             method(s ‐ > Integer.parseInt(s)); 11  } 12     }

 

  (2)默認方法:andThen

    Function 接口中有一個默認的 andThen 方法,用來進行組合操作。JDK源代碼如:

1 default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { 2  Objects.requireNonNull(after); 3     return (T t) ‐> after.apply(apply(t)); 4 }

 

     該方法同樣用於先做什么,再做什么的場景,和 Consumer 中的 andThen 差不多:

 1 import java.util.function.Function;  2 
 3     public class Demo12FunctionAndThen {  4         private static void method(Function<String, Integer> one, Function<Integer, Integer> two) {  5             int num = one.andThen(two).apply("10");  6             System.out.println(num + 20);  7  }  8 
 9         public static void main(String[] args) { 10             method(str‐ > Integer.parseInt(str) + 10, i ‐>i *= 10); 11  } 12     }

  第一個操作是將字符串解析成為int數字,第二個操作是乘以10。兩個操作通過 andThen 按照前后順序組合到了一起。

   注意Function的前置條件泛型和后置條件泛型可以相同。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM