天天看點

day23【函數式接口】-筆記day23【函數式接口】第一章 函數式接口第二章 函數式程式設計第三章 常用函數式接口

day23【函數式接口】

主要内容

自定義函數式接口

函數式程式設計

常用函數式接口

教學目标

能夠使用@FunctionalInterface注解

能夠自定義無參無傳回函數式接口

能夠自定義有參有傳回函數式接口

能夠了解Lambda延遲執行的特點

能夠使用Lambda作為方法的參數

能夠使用Lambda作為方法的傳回值

能夠使用Supplier函數式接口

能夠使用Consumer函數式接口

能夠使用Function函數式接口

能夠使用Predicate函數式接口

第一章 函數式接口

1.1 概念

函數式接口在Java中是指:有且僅有一個抽象方法的接口。

函數式接口,即适用于函數式程式設計場景的接口。而Java中的函數式程式設計展現就是Lambda,是以函數式接口就是可以适用于Lambda使用的接口。隻有確定接口中有且僅有一個抽象方法,Java中的Lambda才能順利地進行推導。

備注:“文法糖”是指使用更加友善,但是原理不變的代碼文法。例如在周遊集合時使用的for-each文法,其實底層的實作原理仍然是疊代器,這便是“文法糖”。從應用層面來講,Java中的Lambda可以被當做是匿名内部類的“文法糖”,但是二者在原理上是不同的。

1.2 格式

隻要確定接口中有且僅有一個抽象方法即可:

 修飾符 interface 接口名稱 {

           public abstract 傳回值類型 方法名稱(可選參數資訊);

            // 其他非抽象方法内容

 }
           

由于接口當中抽象方法的 public abstract 是可以省略的,是以定義一個函數式接口很簡單:

public interface MyFunctionalInterface {   

        void myMethod();    

        }
           

1.3 @FunctionalInterface注解

與 @Override 注解的作用類似,Java 8中專門為函數式接口引入了一個新的注解: @FunctionalInterface 。該注解可用于一個接口的定義上:

@FunctionalInterface

public interface MyFunctionalInterface {

        void myMethod();    

        }
           

一旦使用該注解來定義接口,編譯器将會強制檢查該接口是否确實有且僅有一個抽象方法,否則将會報錯。需要注意的是,即使不使用該注解,隻要滿足函數式接口的定義,這仍然是一個函數式接口,使用起來都一樣。

1.4 自定義函數式接口

對于剛剛定義好的 MyFunctionalInterface 函數式接口,典型使用場景就是作為方法的參數:

public class Demo09FunctionalInterface {   

// 使用自定義的函數式接口作為方法參數    

private static void doSomething(MyFunctionalInterface inter) {    

    inter.myMethod(); // 調用自定義的函數式接口方法        

        }    

           

public static void main(String[] args) {    

        // 調用使用函數式接口的方法        

    doSomething(() ‐> System.out.println("Lambda執行啦!"));        

        }    

        }
           

第二章 函數式程式設計

在兼顧面向對象特性的基礎上,Java語言通過Lambda表達式與方法引用等,為開發者打開了函數式程式設計的大門。下面我們做一個初探。

2.1 Lambda的延遲執行

有些場景的代碼執行後,結果不一定會被使用,進而造成性能浪費。而Lambda表達式是延遲執行的,這正好可以作為解決方案,提升性能。

性能浪費的日志案例

注:日志可以幫助我們快速的定位問題,記錄程式運作過程中的情況,以便項目的監控和優化。

一種典型的場景就是對參數進行有條件使用,例如對日志消息進行拼接後,在滿足條件的情況下進行列印輸出:

public class Demo01Logger {

        private static void log(int level, String msg) {

                if (level == 1) {

                   System.out.println(msg);  

                }

            }

            public static void main(String[] args) {

                String msgA = "Hello";

                String msgB = "World";

                String msgC = "Java";

                log(1, msgA + msgB + msgC);

            }

        }
           

這段代碼存在問題:無論級别是否滿足要求,作為 log 方法的第二個參數,三個字元串一定會首先被拼接并傳入方法内,然後才會進行級别判斷。如果級别不符合要求,那麼字元串的拼接操作就白做了,存在性能浪費。

備注:SLF4J是應用非常廣泛的日志架構,它在記錄日志時為了解決這種性能浪費的問題,并不推薦首先進行字元串的拼接,而是将字元串的若幹部分作為可變參數傳入方法中,僅在日志級别滿足要求的情況下才會進行字元串拼接。例如: LOGGER.debug("變量{}的取值為{}。", "os", "macOS") ,其中的大括号 {} 為占位符。如果滿足日志級别要求,則會将“os”和“macOS”兩個字元串依次拼接到大括号的位置;否則不會進行字元串拼接。這也是一種可行解決方案,但Lambda可以做到更好。

體驗Lambda的更優寫法

使用Lambda必然需要一個函數式接口:

@FunctionalInterface

public interface MessageBuilder { 

           String buildMessage();

        }
           

然後對 log 方法進行改造:

public class Demo02LoggerLambda {

        private static void log(int level, MessageBuilder builder) {

          if (level == 1) {

            System.out.println(builder.buildMessage());  

                }

            }

public static void main(String[] args) {

                String msgA = "Hello";

                String msgB = "World";

                String msgC = "Java";

                log(1, () ‐> msgA + msgB + msgC );

            }

        }
           
這樣一來,隻有當級别滿足要求的時候,才會進行三個字元串的拼接;否則三個字元串将不會進行拼接。
           

證明Lambda的延遲

下面的代碼可以通過結果進行驗證:
           
public class Demo03LoggerDelay {

    private static void log(int level, MessageBuilder builder) {

                if (level == 1) {

           System.out.println(builder.buildMessage());  

                }

            }

            public static void main(String[] args) {

                String msgA = "Hello";

                String msgB = "World";

                String msgC = "Java";

                log(2, () ‐> {

                    System.out.println("Lambda執行!");

                    return msgA + msgB + msgC;

                });

            }

        }
           

從結果中可以看出,在不符合級别要求的情況下,Lambda将不會執行。進而達到節省性能的效果。

擴充:實際上使用内部類也可以達到同樣的效果,隻是将代碼操作延遲到了另外一個對象當中通過調用方法來完成。而是否調用其所在方法是在條件判斷之後才執行的。

2.2 使用Lambda作為參數和傳回值

如果抛開實作原理不說,Java中的Lambda表達式可以被當作是匿名内部類的替代品。如果方法的參數是一個函數式接口類型,那麼就可以使用Lambda表達式進行替代。使用Lambda表達式作為方法參數,其實就是使用函數式接口作為方法參數。

例如 java.lang.Runnable 接口就是一個函數式接口,假設有一個 startThread 方法使用該接口作為參數,那麼就可以使用Lambda進行傳參。這種情況其實和 Thread 類的構造方法參數為 Runnable 沒有本質差別。

public class Demo04Runnable {

            private static void startThread(Runnable task) {

               new Thread(task).start();  

            }

            public static void main(String[] args) {

         startThread(() ‐> System.out.println("線程任務執行!"));  

            }

        }
           

類似地,如果一個方法的傳回值類型是一個函數式接口,那麼就可以直接傳回一個Lambda表達式。當需要通過一個方法來擷取一個 java.util.Comparator 接口類型的對象作為排序器時,就可以調該方法擷取。

import java.util.Arrays;

import java.util.Comparator;

public class Demo06Comparator {

            private static Comparator<String> newComparator() {

               return (a, b) ‐> b.length() ‐ a.length();  

            }

            public static void main(String[] args) {

                String[] array = { "abc", "ab", "abcd" };

                System.out.println(Arrays.toString(array));

                Arrays.sort(array, newComparator());

                System.out.println(Arrays.toString(array));

            }

        }
           

其中直接return一個Lambda表達式即可。

第三章 常用函數式接口

JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景,它們主要在 java.util.function 包中被提供。

下面是最簡單的幾個接口及使用示例。

3.1 Supplier接口

java.util.function.Supplier<T> 接口僅包含一個無參的方法: T get() 。用來擷取一個泛型參數指定類型的對象資料。由于這是一個函數式接口,這也就意味着對應的Lambda表達式需要“對外提供”一個符合泛型類型的對象資料。

import java.util.function.Supplier;

public class Demo08Supplier {

            private static String getString(Supplier<String> function) {

               return function.get();  

            }

            public static void main(String[] args) {

                String msgA = "Hello";

                String msgB = "World";

                System.out.println(getString(() ‐> msgA + msgB));

            }

        }
           

3.2 練習:求數組元素最大值

題目

使用 Supplier 接口作為方法參數類型,通過Lambda表達式求出int數組中的最大值。提示:接口的泛型請使用java.lang.Integer 類。

解答

public class Demo02Test {

            //定一個方法,方法的參數傳遞Supplier,泛型使用Integer

            public static int getMax(Supplier<Integer> sup){

                return sup.get();

            }

            public static void main(String[] args) {

                int arr[] = {2,3,4,52,333,23};

                //調用getMax方法,參數傳遞Lambda

                int maxNum = getMax(()‐>{

                   //計算數組的最大值

                   int max = arr[0];

                   for(int i : arr){

                       if(i>max){

                           max = i;

                       }

                   }

                   return max;

                });

                System.out.println(maxNum);

            }

        }
           

3.3 Consumer接口

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

抽象方法:accept

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

import java.util.function.Consumer;

public class Demo09Consumer {

            private static void consumeString(Consumer<String> function) {

               function.accept("Hello");  

            }

            public static void main(String[] args) {

                consumeString(s ‐> System.out.println(s));

            }

        }
           

當然,更好的寫法是使用方法引用。

預設方法:andThen

如果一個方法的參數和傳回值全都是 Consumer 類型,那麼就可以實作效果:消費資料的時候,首先做一個操作,然後再做一個操作,實作組合。而這個方法就是 Consumer 接口中的default方法 andThen 。下面是JDK的源代碼:

default Consumer<T> andThen(Consumer<? super T> after) {

            Objects.requireNonNull(after);

            return (T t) ‐> { accept(t); after.accept(t); };

        }
           
備注: java.util.Objects 的 requireNonNull 靜态方法将會在參數為null時主動抛出NullPointerException 異常。這省去了重複編寫if語句和抛出空指針異常的麻煩。
           
要想實作組合,需要兩個或多個Lambda表達式即可,而 andThen 的語義正是“一步接一步”操作。例如兩個步驟組合的情況:
           
import java.util.function.Consumer;

public class Demo10ConsumerAndThen {

            private static void consumeString(Consumer<String> one, Consumer<String> two) {

               one.andThen(two).accept("Hello");  

            }

            public static void main(String[] args) {

                consumeString(

                    s ‐> System.out.println(s.toUpperCase()),

                    s ‐> System.out.println(s.toLowerCase()));

            }

        }
           
運作結果将會首先列印完全大寫的HELLO,然後列印完全小寫的hello。當然,通過鍊式寫法可以實作更多步驟的組合。
           

3.4 練習:格式化列印資訊

題目

下面的字元串數組當中存有多條資訊,請按照格式“ 姓名:XX。性别:XX。 ”的格式将資訊列印出來。要求将列印姓名的動作作為第一個 Consumer 接口的Lambda執行個體,将列印性别的動作作為第二個 Consumer 接口的Lambda執行個體,将兩個 Consumer 接口按照順序“拼接”到一起。
           
public static void main(String[] args) {

     String[] array = { "迪麗熱巴,女", "古力娜紮,女", "馬爾紮哈,男" };  

        }
           

解答

import java.util.function.Consumer;

public class DemoConsumer {

      public static void main(String[] args) {

        String[] array = { "迪麗熱巴,女", "古力娜紮,女", "馬爾紮哈,男" };

        printInfo(s ‐> System.out.print("姓名:" + s.split(",")[0]),

         s ‐> System.out.println("。性别:" + s.split(",")[1] + "。"),

                          array);

            }

            private static void printInfo(Consumer<String> one, Consumer<String> two, String[] array) {

                for (String info : array) {

                    one.andThen(two).accept(info); // 姓名:迪麗熱巴。性别:女。

                }

            }

        }
           

3.5 Predicate接口

有時候我們需要對某種類型的資料進行判斷,進而得到一個boolean值結果。這時可以使用

java.util.function.Predicate<T> 接口。

抽象方法:test

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

import java.util.function.Predicate;

public class Demo15PredicateTest {

            private static void method(Predicate<String> predicate) {

                boolean veryLong = predicate.test("HelloWorld");

                System.out.println("字元串很長嗎:" + veryLong);

            }

            public static void main(String[] args) {

                method(s ‐> s.length() > 5);

            }

        }
           

條件判斷的标準是傳入的Lambda表達式邏輯,隻要字元串長度大于5則認為很長。

預設方法:and

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

default Predicate<T> and(Predicate<? super T> other) {

            Objects.requireNonNull(other);

            return (t) ‐> test(t) && other.test(t);

        }
           

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

import java.util.function.Predicate;

public class Demo16PredicateAnd {

            private static void method(Predicate<String> one, Predicate<String> two) {

                boolean isValid = one.and(two).test("Helloworld");

                System.out.println("字元串符合要求嗎:" + isValid);

            }

            public static void main(String[] args) {

                method(s ‐> s.contains("H"), s ‐> s.contains("W"));

            }

        }
           

預設方法:or

與 and 的“與”類似,預設方法 or 實作邏輯關系中的“或”。JDK源碼為:

default Predicate<T> or(Predicate<? super T> other) {

            Objects.requireNonNull(other);

            return (t) ‐> test(t) || other.test(t);

        }
           

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

import java.util.function.Predicate;

public class Demo16PredicateAnd {

            private static void method(Predicate<String> one, Predicate<String> two) {

                boolean isValid = one.or(two).test("Helloworld");

                System.out.println("字元串符合要求嗎:" + isValid);

            }

            public static void main(String[] args) {

                method(s ‐> s.contains("H"), s ‐> s.contains("W"));

            }

        }
           

預設方法:negate

“與”、“或”已經了解了,剩下的“非”(取反)也會簡單。預設方法 negate 的JDK源代碼為:

default Predicate<T> negate() {

            return (t) ‐> !test(t);

        }
           

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

import java.util.function.Predicate;

public class Demo17PredicateNegate {

            private static void method(Predicate<String> predicate) {

                boolean veryLong = predicate.negate().test("HelloWorld");

                System.out.println("字元串很長嗎:" + veryLong);

            }

            public static void main(String[] args) {

               method(s ‐> s.length() < 5);  

            }

        }
           

3.6 練習:集合資訊篩選

題目

數組當中有多條“姓名+性别”的資訊如下,請通過 Predicate 接口的拼裝将符合要求的字元串篩選到集合ArrayList 中,需要同時滿足兩個條件:

1. 必須為女生;

2. 姓名為4個字。

public class DemoPredicate {

            public static void main(String[] args) {

               String[] array = { "迪麗熱巴,女", "古力娜紮,女", "馬爾紮哈,男", "趙麗穎,女" };  

            }

        }
           

解答

import java.util.ArrayList;

import java.util.List;

import java.util.function.Predicate;

public class DemoPredicate {

            public static void main(String[] args) {

                String[] array = { "迪麗熱巴,女", "古力娜紮,女", "馬爾紮哈,男", "趙麗穎,女" };

                List<String> list = filter(array,

                                           s ‐> "女".equals(s.split(",")[1]),

                                           s ‐> s.split(",")[0].length() == 4);

                System.out.println(list);

            }

            private static List<String> filter(String[] array, Predicate<String> one,

                                               Predicate<String> two) {

                List<String> list = new ArrayList<>();

                for (String info : array) {

                    if (one.and(two).test(info)) {

                        list.add(info);

                    }

                }

                return list;

            }

        }
           

3.7 Function接口

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

抽象方法:apply

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

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

import java.util.function.Function;

public class Demo11FunctionApply {

            private static void method(Function<String, Integer> function) {

                int num = function.apply("10");

                System.out.println(num + 20);

            }

            public static void main(String[] args) {

                method(s ‐> Integer.parseInt(s));

            }

        }
           

當然,最好是通過方法引用的寫法。

預設方法:andThen

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

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {

            Objects.requireNonNull(after);

            return (T t) ‐> after.apply(apply(t));

        }
           

該方法同樣用于“先做什麼,再做什麼”的場景,和 Consumer 中的 andThen 差不多:

import java.util.function.Function;

public class Demo12FunctionAndThen {

            private static void method(Function<String, Integer> one, Function<Integer, Integer> two) {

                int num = one.andThen(two).apply("10");

                System.out.println(num + 20);

            }

            public static void main(String[] args) {

                method(str‐>Integer.parseInt(str)+10, i ‐> i *= 10);

            }

        }
           

第一個操作是将字元串解析成為int數字,第二個操作是乘以10。兩個操作通過 andThen 按照前後順序組合到了一起。請注意,Function的前置條件泛型和後置條件泛型可以相同。

3.8 練習:自定義函數模型拼接

題目

請使用 Function 進行函數模型的拼接,按照順序需要執行的多個函數操作為:

String str = "趙麗穎,20";

1. 将字元串截取數字年齡部分,得到字元串;

2. 将上一步的字元串轉換成為int類型的數字;

3. 将上一步的int數字累加100,得到結果int數字。

解答

import java.util.function.Function;

public class DemoFunction {

            public static void main(String[] args) {

                String str = "趙麗穎,20";

                int age = getAgeNum(str, s ‐> s.split(",")[1],

                                    s ‐>Integer.parseInt(s),

                                    n ‐> n += 100);

                System.out.println(age);

            }

            private static int getAgeNum(String str, Function<String, String> one,

                                         Function<String, Integer> two,

                                         Function<Integer, Integer> three) {

                return one.andThen(two).andThen(three).apply(str);

            }

        }