主頁 > 後端開發 > JDK1.8新特性之(三)--函式式介面

JDK1.8新特性之(三)--函式式介面

2020-10-22 08:32:36 後端開發

在上一篇文章中我們介紹了JDK1.8的新特性有以下幾項,

1.Lambda運算式

2.方法參考

3.函式式介面

4.默認方法

5.Stream

6.Optional類

7.Nashorm javascript引擎

8.新的日期時間API

9.Base64

之前學習了前面兩項Lambda運算式,方法參考,這一篇學習函式式介面,

所謂的函式式介面它只能定義一個抽象方法,其他方法可以用default或者static關鍵對方法進行限定,

下面先來通過實體來驗證一下,

自定義一個函式式介面,然后定義一個叫testA的抽象方法,再定義一個叫testB的抽象方法,

  

 此時@FunctionalInterface注解會提示如下錯誤,(在介面中發現有復數個沒有被覆寫的抽象方法)

 那我接下來把testB改為非抽象方法試試,

 發現改完之后又多了一處錯誤,我們繼續看看新出的錯誤,

 接下來我們把方法加上default關鍵字

 這時候就沒有錯誤資訊啦,說明函式式介面中可以除了含有抽象方法外可以有默認的非靜態方法

下面我把default改成static試一試看看可不可以有靜態方法,

此時發現也沒有問題,那就說明函式式介面中還可以有靜態方法

因為Object類是所有類的父類,所有介面中能被重寫的方法都可以在介面中定義,比如

toString,equals方法,

了解完函式式介面,接下來說一下API內置的四大函式式介面, 

主要就以下

1. Consumer -- 消費性介面

2. Supplier -- 供給型介面

3. Function -- 函式型介面

4. Predicate -- 斷言型介面

下面我們依次來看一下API源代碼,以及通過寫實體來理解一下每種型別介面使用方法以及特點,

1. Consumer(有傳入,沒有傳出的時候使用)

官方源代碼如下,為了起來方便簡潔把開頭的注釋去掉了,只保留了方法的注釋,

 1 package java.util.function;
 2 
 3 import java.util.Objects;
 4 
 5 @FunctionalInterface
 6 public interface Consumer<T> {
 7 
 8     /**
 9      * Performs this operation on the given argument.
10      *
11      * @param t the input argument
12      */
13     void accept(T t);
14 
15     /**
16      * Returns a composed {@code Consumer} that performs, in sequence, this
17      * operation followed by the {@code after} operation. If performing either
18      * operation throws an exception, it is relayed to the caller of the
19      * composed operation.  If performing this operation throws an exception,
20      * the {@code after} operation will not be performed.
21      *
22      * @param after the operation to perform after this operation
23      * @return a composed {@code Consumer} that performs in sequence this
24      * operation followed by the {@code after} operation
25      * @throws NullPointerException if {@code after} is null
26      */
27     default Consumer<T> andThen(Consumer<? super T> after) {
28         Objects.requireNonNull(after);
29         return (T t) -> { accept(t); after.accept(t); };
30     }
31 }

直接看accept抽象方法,接收一個泛型T型別的t,回傳值型別是void,我們把它叫做消費型介面,特點就是有去無回,

下面我們直接看實體

 1 public class InfixFunctionTest {
 2     //1.消費型介面
 3     @Test
 4     public void test1(){
 5         //把傳入的字串列印
 6         Consumer<String> con = x -> System.out.println(x);//定義函式式的實作
 7         con.accept("Hello Consumer!");//接收引數
 8     }
 9 
10 }

執行結果

com.dream.test.JDK8speciality.InfixFunctionTest,test1
Hello Consumer!

Process finished with exit code 0

我們只需要在Lambda運算式的引數串列中傳入一個x,然后實作是:得到一個無回傳型別的列印陳述句,

2. Supplier(沒有傳入,有傳出的時候使用)

官方原始碼

 1 package java.util.function;
 2 
 3 /**
 4  * Represents a supplier of results.
 5  *
 6  * <p>There is no requirement that a new or distinct result be returned each
 7  * time the supplier is invoked.
 8  *
 9  * <p>This is a <a href="https://www.cnblogs.com/worthycoder/p/package-summary.html">functional interface</a>
10  * whose functional method is {@link #get()}.
11  *
12  * @param <T> the type of results supplied by this supplier
13  *
14  * @since 1.8
15  */
16 @FunctionalInterface
17 public interface Supplier<T> {
18 
19     /**
20      * Gets a result.
21      *
22      * @return a result
23      */
24     T get();
25 }

get方法沒有傳入引數,回傳一個T,稱為供給型介面,特點就是只求回報不求付出,

實體

 1 public class InfixFunctionTest {
 2 
 3     //2.供給型介面
 4     @Test
 5     public void test2(){
 6         Supplier<String> su = () -> new String();
 7         String str = su.get();
 8         System.out.println("供給型介面的值:" + str);
 9     }
10 
11 }

執行結果

com.dream.test.JDK8speciality.InfixFunctionTest,test2
供給型介面的值:

Process finished with exit code 0

我們在Lambda運算式傳入引數用()代表沒有引數傳入,然后回傳一個String型別的物件,

3.Function(有傳入引數,傳出的時候使用)

官方原始碼

 1 package java.util.function;
 2 
 3 import java.util.Objects;
 4 
 5 /**
 6  * Represents a function that accepts one argument and produces a result.
 7  *
 8  * <p>This is a <a href="https://www.cnblogs.com/worthycoder/p/package-summary.html">functional interface</a>
 9  * whose functional method is {@link #apply(Object)}.
10  *
11  * @param <T> the type of the input to the function
12  * @param <R> the type of the result of the function
13  *
14  * @since 1.8
15  */
16 @FunctionalInterface
17 public interface Function<T, R> {
18 
19     /**
20      * Applies this function to the given argument.
21      *
22      * @param t the function argument
23      * @return the function result
24      */
25     R apply(T t);
26 
27     /**
28      * Returns a composed function that first applies the {@code before}
29      * function to its input, and then applies this function to the result.
30      * If evaluation of either function throws an exception, it is relayed to
31      * the caller of the composed function.
32      *
33      * @param <V> the type of input to the {@code before} function, and to the
34      *           composed function
35      * @param before the function to apply before this function is applied
36      * @return a composed function that first applies the {@code before}
37      * function and then applies this function
38      * @throws NullPointerException if before is null
39      *
40      * @see #andThen(Function)
41      */
42     default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
43         Objects.requireNonNull(before);
44         return (V v) -> apply(before.apply(v));
45     }
46 
47     /**
48      * Returns a composed function that first applies this function to
49      * its input, and then applies the {@code after} function to the result.
50      * If evaluation of either function throws an exception, it is relayed to
51      * the caller of the composed function.
52      *
53      * @param <V> the type of output of the {@code after} function, and of the
54      *           composed function
55      * @param after the function to apply after this function is applied
56      * @return a composed function that first applies this function and then
57      * applies the {@code after} function
58      * @throws NullPointerException if after is null
59      *
60      * @see #compose(Function)
61      */
62     default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
63         Objects.requireNonNull(after);
64         return (T t) -> after.apply(apply(t));
65     }
66 
67     /**
68      * Returns a function that always returns its input argument.
69      *
70      * @param <T> the type of the input and output objects to the function
71      * @return a function that always returns its input argument
72      */
73     static <T> Function<T, T> identity() {
74         return t -> t;
75     }
76 }

Function介面提供了一個抽象方法,兩個默認方法和一個靜態方法,這里我只對最常用的抽象方法做出解釋,

apply方法接收一個T型別的t,回傳一個R型別的值,我們稱之為函式型介面,特點就是你來我往,(俗話說的好,來而不往非禮也!哈哈哈!)

實體

 1 public class InfixFunctionTest {
 2  
 3     //3.函式型介面
 4     @Test
 5     public void test3(){
 6         Function<String,Camera> fun = (x) -> new Camera(x);//Function抽象函式的實作,
 7         Camera camera = fun.apply("Sony-A7R3");//接收傳入的引數
 8         System.out.println("cameraName: " + camera.getCameraName() + " price:" + camera.getPrice());
 9     }
10 
11 }

Camera類

 1 //相機類
 2 class Camera{
 3     //相機名字
 4     private String cameraName;
 5     //相機價格
 6     private Integer price;
 7 
 8     //無引數構造器
 9     public Camera(){
10 
11     }
12 
13     //有引數構造器
14     public Camera(String cameraName){
15         this.cameraName = cameraName;
16     }
17 
18     //有引數構造器
19     public Camera(String cameraName,Integer price){
20         this.cameraName = cameraName;
21         this.price = price;
22     }
23 
24     public String getCameraName() {
25         return cameraName;
26     }
27 
28     public void setCameraName(String cameraName) {
29         this.cameraName = cameraName;
30     }
31 
32     public Integer getPrice() {
33         return price;
34     }
35 
36     public void setPrice(Integer price) {
37         this.price = price;
38     }
39 }

執行結果

com.dream.test.JDK8speciality.InfixFunctionTest,test3
cameraName: Sony-A7R3 price:null

Process finished with exit code 0

Lam運算式中傳入一個引數x,然后x作為構造器的引數,回傳一個Camera物件,

4.Predicate(傳入一個引數,回傳一個布爾型別的結果)

 官網原始碼

 1 package java.util.function;
 2 
 3 import java.util.Objects;
 4 
 5 /**
 6  * Represents a predicate (boolean-valued function) of one argument.
 7  *
 8  * <p>This is a <a href="https://www.cnblogs.com/worthycoder/p/package-summary.html">functional interface</a>
 9  * whose functional method is {@link #test(Object)}.
10  *
11  * @param <T> the type of the input to the predicate
12  *
13  * @since 1.8
14  */
15 @FunctionalInterface
16 public interface Predicate<T> {
17 
18     /**
19      * Evaluates this predicate on the given argument.
20      *
21      * @param t the input argument
22      * @return {@code true} if the input argument matches the predicate,
23      * otherwise {@code false}
24      */
25     boolean test(T t);
26 
27     /**
28      * Returns a composed predicate that represents a short-circuiting logical
29      * AND of this predicate and another.  When evaluating the composed
30      * predicate, if this predicate is {@code false}, then the {@code other}
31      * predicate is not evaluated.
32      *
33      * <p>Any exceptions thrown during evaluation of either predicate are relayed
34      * to the caller; if evaluation of this predicate throws an exception, the
35      * {@code other} predicate will not be evaluated.
36      *
37      * @param other a predicate that will be logically-ANDed with this
38      *              predicate
39      * @return a composed predicate that represents the short-circuiting logical
40      * AND of this predicate and the {@code other} predicate
41      * @throws NullPointerException if other is null
42      */
43     default Predicate<T> and(Predicate<? super T> other) {
44         Objects.requireNonNull(other);
45         return (t) -> test(t) && other.test(t);
46     }
47 
48     /**
49      * Returns a predicate that represents the logical negation of this
50      * predicate.
51      *
52      * @return a predicate that represents the logical negation of this
53      * predicate
54      */
55     default Predicate<T> negate() {
56         return (t) -> !test(t);
57     }
58 
59     /**
60      * Returns a composed predicate that represents a short-circuiting logical
61      * OR of this predicate and another.  When evaluating the composed
62      * predicate, if this predicate is {@code true}, then the {@code other}
63      * predicate is not evaluated.
64      *
65      * <p>Any exceptions thrown during evaluation of either predicate are relayed
66      * to the caller; if evaluation of this predicate throws an exception, the
67      * {@code other} predicate will not be evaluated.
68      *
69      * @param other a predicate that will be logically-ORed with this
70      *              predicate
71      * @return a composed predicate that represents the short-circuiting logical
72      * OR of this predicate and the {@code other} predicate
73      * @throws NullPointerException if other is null
74      */
75     default Predicate<T> or(Predicate<? super T> other) {
76         Objects.requireNonNull(other);
77         return (t) -> test(t) || other.test(t);
78     }
79 
80     /**
81      * Returns a predicate that tests if two arguments are equal according
82      * to {@link Objects#equals(Object, Object)}.
83      *
84      * @param <T> the type of arguments to the predicate
85      * @param targetRef the object reference with which to compare for equality,
86      *               which may be {@code null}
87      * @return a predicate that tests if two arguments are equal according
88      * to {@link Objects#equals(Object, Object)}
89      */
90     static <T> Predicate<T> isEqual(Object targetRef) {
91         return (null == targetRef)
92                 ? Objects::isNull
93                 : object -> targetRef.equals(object);
94     }
95 }

Predicate介面提供了一個抽象方法,三個默認方法和一個靜態方法,這里是對抽象方法進行舉例說明,

由于回傳一個布爾型別的值,我們稱之為斷言型,特點就是發出請求,等待指示(做還是不做,哈哈),

 1 public class InfixFunctionTest {
 2 
 3     //4.斷言式介面
 4     @Test
 5     public void test4(){
 6         Predicate<String> pre = x -> x == null;
 7         Boolean b =pre.test(null);
 8         System.out.println("斷言式測驗結果:" + b);
 9     }
10 
11 }

執行結果

com.dream.test.JDK8speciality.InfixFunctionTest,test4
斷言式測驗結果:true

Process finished with exit code 0

Lambda運算式傳入一個引數x,判斷x是不是null,

以上實體中都省略了頭部的打包和匯入包資訊,包資訊如下,

1 package com.dream.test.JDK8speciality;
2 
3 import org.junit.Test;
4 
5 import java.util.function.Consumer;
6 import java.util.function.Function;
7 import java.util.function.Predicate;
8 import java.util.function.Supplier;

 

java.util.function包下除了上面這幾個基本函式式介面外,還有好多,其他的都是這幾個基本的衍生,這幾個搞懂了,其他的就都不難理解了,有興趣的可以自己進行研究,

以上就是對函式式的學習,如果各位大神發現有不對或者不好的地方,歡迎指正,非常感謝!

上一篇文章

JDK1.8新特性之(二)--方法參考

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/185235.html

標籤:Java

上一篇:LeetCode 面試題33. 二叉搜索樹的后序遍歷序列

下一篇:LeetCode 34. 在排序陣列中查找元素的第一個和最后一個位置

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more