Java筆記12-函數式接口

主要內容

  • 自定義函數式接口
  • 函數式編程
  • 經常使用函數式接口

第一章 函數式接口

概念

函數式接口在java中指的是:有且只有一個抽象方法的接口java

函數式接口,即適用於函數式編程場景的接口.而java中共的函數式編程體現就是Lambda,因此函數式接口就是能夠適用於lambda使用的接口.只有確保接口中有且只有一個寵幸方法,java中的lambda才能順利地進行推導.web

備註:語法糖是指使用更加方便,可是原理不變的代碼語法,例如在遍歷集合時使用for-each語法,其實底層的實現原理仍然是迭代器,這即是語法糖.從應用應用層面來京,java中的lambda能夠被當作是匿名內部類了的語法糖,可是兩者原理上是不一樣的.編程

格式

只要確保接口中有且僅有一個抽象方法便可:數組

修飾符 Interface 接口名稱{
    public abstract 返回值類型 方法名稱(可選參數信息);
    // 其餘非抽象方法內容
}

因爲接口當中抽象方法的public abstract 是能夠省略的,因此定義一函數式接口很簡單:框架

public Interface MyFunctionalInterface{
    void myMethod();
}

@FunctionalInterface註解

@Override註解的做用相似,Java 8 中專門爲函數式接口引入了一個新的註解:@FunctionInterface.該註解可用於一個接口的定義上:ide

@FunctionalInterface
public interface MyFunctionalInterface{
    void myMethod();
}

一旦使用該註解來定義接口,編譯期將會強制檢查該接口是否確實有且僅有一個抽象方法,不然將會報錯.須要注意的是,即便不使用該註解,主要知足函數式接口的定義,這仍然是一個函數式接口,使用起來都一個B樣,只不過@FunctionalInterface用起來規範一點,說白了逼格高那麼一丟丟svg

自定義函數式接口

對於剛剛定義好的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表達式與方法引用等,爲開發者打開了函數式編程的大門函數

下面咱們作一個初探性能

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將不會執行。從而達到節省性能的效果。

擴展:實際上使用內部類也能夠達到一樣的效果,只是將代碼操做延遲到了另一個對象當中經過調用方法來完成。而是否調用其所在方法是在條件判斷以後才執行的。

使用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 包中被提供。 下面是最簡單的幾個接口及使用示例。

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));
   } 
}

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

題目:

使用 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);
    }
}

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。固然,經過鏈式寫法能夠實現更多步驟的 組合。

練習:格式化打印信息

題目
下面的字符串數組當中存有多條信息,請按照格式「 姓名: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); // 姓名:迪麗熱巴。性別:女。 
        }
    } 
}

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 方法,正如 andor 方法同樣:

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);
} 
}

練習:集合信息篩選 題目

數組當中有多條「姓名+性別」的信息以下,請經過 Predicate 接口的拼裝將符合要求的字符串篩選到集合 ArrayList 中,須要同時知足兩個條件:

    1. 必須爲女生;
    1. 姓名爲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;
   }
}
相關文章
相關標籤/搜索