一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|

服務器之家 - 編程語言 - JAVA教程 - 詳解JAVA 函數式編程

詳解JAVA 函數式編程

2020-07-14 17:57奇奇鋒 JAVA教程

這篇文章主要介紹了JAVA 函數式編程的相關資料,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下

1.函數式接口

1.1概念:

java中有且只有一個抽象方法的接口。

1.2格式:

?
1
2
3
4
5
6
7
8
9
10
修飾符 interface 接口名稱 {
public abstract 返回值類型 方法名稱(可選參數信息);
// 其他非抽象方法內容
 }
 
//或者
 
public interface MyFunctionalInterface {
void myMethod();
 }

1.3@FunctionalInterface注解:

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

?
1
2
3
4
@FunctionalInterface
public interface MyFunctionalInterface {
void myMethod();
}

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

1.4自定義函數式接口

?
1
2
3
4
5
6
7
public class Demo09FunctionalInterface {
// 使用自定義的函數式接口作為方法參數
private static void doSomething(MyFunctionalInterface inter) { inter.myMethod(); // 調用自定義的函數式接口方法
}
public static void main(String[] args) {
// 調用使用函數式接口的方法 doSomething(() ‐> System.out.println("Lambda執行啦!"));
} }

2.函數式編程

2.1 Lambda的延遲執行

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

性能浪費的日志案例

注:日志可以幫助我們快速的定位問題,記錄程序運行過程中的情況,以便項目的監控和優化。
一種典型的場景就是對參數進行有條件使用,例如對日志消息進行拼接后,在滿足條件的情況下進行打印輸出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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必然需要一個函數式接口:

?
1
2
3
4
@FunctionalInterface
public interface MessageBuilder {
  String buildMessage();
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
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的延遲

下面的代碼可以通過結果進行驗證

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 沒有本質區別。

?
1
2
3
4
5
6
7
8
9
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 接口類型的對象作為排序器時,就可以調該方法獲取。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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表達式即可。

3.常用函數式接口

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

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

3.1 Supplier接口(求數組元素最大值)

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

求數組元素最大值

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.2 Consumer接口

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

抽象方法:accept

Consumer 接

?
1
2
3
4
5
6
7
8
9
10
11
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的源代碼:口中包含抽象方法 void accept(T t) ,意為消費一個指定泛型的數據。基本使用如:

格式化打印信息

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.3 Predicate接口

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

抽象方法:test

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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);
    }
  }

默認方法:and

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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源碼為:

?
1
2
3
4
5
6
7
8
9
10
11
12
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源代碼為:從實現中很容易看出,它是執行了test方法之后,對結果boolean值進行“!”取反而已。一定要在 test 方法調用之前調用 negate 方法,正如 and 和 or 方法一樣:

?
1
2
3
4
5
6
7
8
9
10
11
12
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. 必須為女生;

2. 姓名為4個字。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.4 Function接口

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

抽象方法:apply

Function 接口中最主要的抽象方法為: R apply(T t) ,根據類型T的參數獲取類型R的結果。使用的場景例如:將 String 類型轉換為 Integer 類型。

?
1
2
3
4
5
6
7
8
9
10
11
12
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 方法,用來進行組合操作。

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

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

String str = "趙麗穎,20";

1. 將字符串截取數字年齡部分,得到字符串;
2. 將上一步的字符串轉換成為int類型的數字;
3. 將上一步的int數字累加100,得到結果int數字。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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);
    }
  }

以上就是詳解JAVA 函數式編程的詳細內容,更多關于JAVA 函數式編程的資料請關注服務器之家其它相關文章!

原文鏈接:https://www.cnblogs.com/qqfff/p/13204395.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 91chinese 永久免费 | 2020国产精品永久在线观看 | 五月色婷婷久久综合 | 成年女人毛片免费观看97 | 欧美日韩精品乱国产 | 国产好深好硬好爽我还要视频 | 香蕉久久久久久狠狠色 | 日本一区二区免费在线 | 国产一久久香蕉国产线看观看 | 亚洲国内精品久久 | 国产福利在线观看91精品 | 成人久久18免费网站入口 | 国产卡一卡二卡三卡四 | 催眠 迷j系列小说 | 成人综合久久综合 | 海绵宝宝第二季全集免费观看 | 果冻传媒在线视频观看免费 | 继攵催眠女乱h调教 | 色综合久久夜色精品国产 | 国产精品永久免费视频 | 日韩精品一区二区三区免费视频 | 香港三级浴室女警官 | 99re热这里只有精品视频 | 好看华人华人经典play | 欧美日韩中文字幕一区二区高清 | 亚洲福利视频在线观看 | 99久久6er热免费精品 | 色中色破解版 | 精品国产一区二区三区在线观看 | 日本卡一卡2卡3卡4精品卡无人区 | 久久成人a毛片免费观看网站 | 草草草视频在线观看 | 亚洲国产精品一区二区久久 | 欧美伊人久久久久久久久影院 | 91久久偷偷做嫩草影院免费看 | 日韩中文字幕视频在线观看 | 男人猛激烈吃奶gif动态图 | 福利一区在线观看 | 亚洲人成毛片线播放 | 黑人巨大爆粗亚裔女人 | 全色黄大色黄大片爽一次 |