日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

Java中的函數接口,你都用過了嗎

來源: 責編: 時間:2023-12-22 17:12:46 228觀看
導讀在這篇文章中,我們將通過示例來學習 Java 函數式接口。一、函數式接口的特點只包含一個抽象方法的接口稱為函數式接口。它可以有任意數量的默認靜態方法,但只能包含一個抽象方法。它還可以聲明對象類的方法。函數接口也

在這篇文章中,我們將通過示例來學習 Java 函數式接口。Qpc28資訊網——每日最新資訊28at.com

一、函數式接口的特點

  • 只包含一個抽象方法的接口稱為函數式接口。
  • 它可以有任意數量的默認靜態方法,但只能包含一個抽象方法。它還可以聲明對象類的方法。
  • 函數接口也稱為單一抽象方法接口或SAM 接口。
  • 函數式接口只有在沒有任何抽象方法時才可以擴展另一個接口。
  • Java API 具有許多單方法接口,例如 Runnable、Callable、Comparator、ActionListener等。它們可以使用匿名類語法來實現和實例化。

Qpc28資訊網——每日最新資訊28at.com

二、接口示例

創建一個自定義的Sayable接口,這是一個使用@FunctionalInterface注解的函數式接口。@FunctionalInterface注解表示該接口是一個函數式接口,并且只包含一個抽象方法。Qpc28資訊網——每日最新資訊28at.com

1.自定義函數接口示例:

@FunctionalInterface  interface Sayable{      void say(String msg);   // abstract method   }  

讓我們通過main()方法來演示一個自定義的函數式接口。我們使用Lambda表達式來實現函數式接口。Qpc28資訊網——每日最新資訊28at.com

public class FunctionalInterfacesExample {    public static void main(String[] args) {        Sayable sayable = (msg) -> {            System.out.println(msg);        };        sayable.say("Say something ..");    }}

2.Predefined 函數接口

Java提供了Predefined的函數式接口,通過使用 lambda 和方法引用來處理函數式編程。Qpc28資訊網——每日最新資訊28at.com

Predicate是檢查條件的函數,它接受一個參數并返回boolean結果。Qpc28資訊網——每日最新資訊28at.com

讓我們來看一下Predicate接口的內部實現。Qpc28資訊網——每日最新資訊28at.com

import java.util.function.Predicate;public interface Predicate<T> {    boolean test(T t);    default Predicate<T> and(Predicate<? super T> other) {        // 默認方法的實現        return (t) -> test(t) && other.test(t);    }    // 其他默認方法和靜態方法...}

Predicate接口只包含一個抽象方法test(T t)同時它還包含默認方法和靜態方法。Qpc28資訊網——每日最新資訊28at.com

讓我們創建一個示例來演示Predicate函數式接口的用法:Qpc28資訊網——每日最新資訊28at.com

import java.util.Arrays;import java.util.List;import java.util.function.Predicate;public class Main {    public static void main(String[] args) {        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);        // 使用Predicate接口檢查數字是否為偶數        Predicate<Integer> evenNumberPredicate = number -> number % 2 == 0;        System.out.println("Even numbers:");        printNumbers(numbers, evenNumberPredicate);        // 使用Predicate接口檢查數字是否大于5        Predicate<Integer> greaterThanFivePredicate = number -> number > 5;        System.out.println("Numbers greater than 5:");        printNumbers(numbers, greaterThanFivePredicate);    }    public static void printNumbers(List<Integer> numbers, Predicate<Integer> predicate) {        for (Integer number : numbers) {            if (predicate.test(number)) {                System.out.println(number);            }        }    }}

3.Function 函數接口

Function函數接口是Java中的一個函數式接口,它定義了一個接收一個參數并返回結果的函數。它的定義如下:Qpc28資訊網——每日最新資訊28at.com

@FunctionalInterfacepublic interface Function<T, R> {    R apply(T t);}

Function接口有兩個泛型參數:T表示輸入參數的類型,R表示返回結果的類型。它包含一個抽象方法apply(),接收一個類型為T的參數,并返回一個類型為R的結果。Qpc28資訊網——每日最新資訊28at.com

Function接口常用于將一個值轉換為另一個值,或者對輸入值進行處理和計算。它可以被用于各種場景,如數據轉換、映射、計算和處理等。Qpc28資訊網——每日最新資訊28at.com

以下是一個使用Function函數接口的示例:Qpc28資訊網——每日最新資訊28at.com

import java.util.function.Function;public class Main {    public static void main(String[] args) {        // 創建一個Function接口來將字符串轉換為大寫        Function<String, String> uppercaseFunction = str -> str.toUpperCase();        // 使用Function接口將字符串轉換為大寫        String result = uppercaseFunction.apply("hello world");        System.out.println(result);  // 輸出: HELLO WORLD        // 使用Function接口將字符串轉換為其長度        Function<String, Integer> lengthFunction = str -> str.length();        int length = lengthFunction.apply("hello");        System.out.println(length);  // 輸出: 5    }}

4.Supplier 函數接口

Supplier用于表示一個提供(供應)結果的函數。它通常用于延遲計算或在需要時生成值。通過調用get()方法,我們可以獲取由Supplier實例提供的結果。Qpc28資訊網——每日最新資訊28at.com

以下是Consumer接口的實現Qpc28資訊網——每日最新資訊28at.com

@FunctionalInterfacepublic interface Supplier<T> {    /**     * Gets a result.     *     * @return a result     */    T get();}

由于Supplier接口只有一個抽象方法,因此可以使用lambda表達式快速創建Supplier實例。下面是一個示例:Qpc28資訊網——每日最新資訊28at.com

import java.util.Random;import java.util.function.Supplier;public class Main {    public static void main(String[] args) {        // 創建一個Supplier接口來生成隨機整數        Supplier<Integer> randomIntegerSupplier = () -> new Random().nextInt();        // 使用Supplier接口生成隨機整數        int randomNumber = randomIntegerSupplier.get();        System.out.println(randomNumber);        // 創建一個Supplier接口來生成當前時間戳        Supplier<Long> timestampSupplier = () -> System.currentTimeMillis();        // 使用Supplier接口生成當前時間戳        long timestamp = timestampSupplier.get();        System.out.println(timestamp);    }}

5.Consumer 函數接口

Consumer用于表示接受一個參數并執行某些操作的函數。它定義了一個名為accept(T t)的抽象方法,接受一個參數,并且沒有返回值。Qpc28資訊網——每日最新資訊28at.com

以下是Consumer接口的簡化版本:Qpc28資訊網——每日最新資訊28at.com

@FunctionalInterfacepublic interface Consumer<T> {    void accept(T arg0);}

Consumer接口適用于那些需要對傳入的參數進行某種操作,而不需要返回結果的情況。它可以用于在不同的上下文中執行各種操作,如打印、修改狀態、更新對象等。下面是一個使用Consumer接口的示例:Qpc28資訊網——每日最新資訊28at.com

import java.util.Arrays;import java.util.List;import java.util.function.Consumer;public class Main {    public static void main(String[] args) {        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");        // 使用Consumer接口打印每個名字        Consumer<String> printName = name -> System.out.println(name);        names.forEach(printName);        // 使用Consumer接口修改每個名字為大寫形式        Consumer<String> uppercaseName = name -> {            String uppercase = name.toUpperCase();            System.out.println(uppercase);        };        names.forEach(uppercaseName);    }}

在上述示例中,我們創建了兩個Consumer接口的實例。第一個printName用于打印每個名字,第二個uppercaseName用于將每個名字轉換為大寫形式并打印。Qpc28資訊網——每日最新資訊28at.com

通過調用forEach()方法并傳入相應的Consumer接口實例,我們可以對列表中的每個元素執行相應的操作。在示例中,我們對名字列表中的每個名字進行了打印和轉換操作。Qpc28資訊網——每日最新資訊28at.com

Consumer接口的使用場景包括遍歷集合、處理回調函數、更新對象狀態等。它提供了一種簡潔的方式來執行針對輸入參數的操作,使得代碼更加清晰和模塊化。Qpc28資訊網——每日最新資訊28at.com

6.BiFunction 函數接口

BiFunction函數式接口表示接受兩個參數并返回結果的函數。它定義了一個名為apply(T t, U u)的抽象方法,接受兩個參數,并返回一個結果。Qpc28資訊網——每日最新資訊28at.com

讓我們來看一下BiFunction接口的簡化版本。Qpc28資訊網——每日最新資訊28at.com

@FunctionalInterfacepublic interface BiFunction<T, U, R> {    R apply(T arg0, U arg1);}

BiFunction接口適用于那些需要接受兩個輸入參數并產生結果的情況。它可以用于執行各種操作,如計算、轉換、篩選等。下面是一個使用BiFunction接口的示例:Qpc28資訊網——每日最新資訊28at.com

import java.util.function.BiFunction;public class Main {    public static void main(String[] args) {        // 使用BiFunction接口計算兩個數的和        BiFunction<Integer, Integer, Integer> sumFunction = (a, b) -> a + b;        int sum = sumFunction.apply(5, 3);        System.out.println(sum);  // 輸出: 8        // 使用BiFunction接口將兩個字符串拼接起來        BiFunction<String, String, String> concatenateFunction = (str1, str2) -> str1 + str2;        String result = concatenateFunction.apply("Hello, ", "World!");        System.out.println(result);  // 輸出: Hello, World!    }}

7.BiConsumer函數接口

BiConsumer接口,用于表示接受兩個參數并執行某些操作的函數。它定義了一個名為accept(T t, U u)的抽象方法,接受兩個參數,并且沒有返回值。Qpc28資訊網——每日最新資訊28at.com

以下是BiConsumer接口的簡化版本:Qpc28資訊網——每日最新資訊28at.com

import java.util.function.BiConsumer;@FunctionalInterfacepublic interface BiConsumer<T, U> {    void accept(T t, U u);}

BiConsumer接口適用于那些需要對傳入的兩個參數進行某種操作,而不需要返回結果的情況。它可以用于在不同的上下文中執行各種操作,如打印、修改狀態、更新對象等。下面是一個使用BiConsumer接口的示例:Qpc28資訊網——每日最新資訊28at.com

import java.util.function.BiConsumer;public class Main {    public static void main(String[] args) {        // 使用BiConsumer接口打印兩個數的和        BiConsumer<Integer, Integer> sumPrinter = (a, b) -> System.out.println(a + b);        sumPrinter.accept(5, 3);        // 使用BiConsumer接口打印兩個字符串的拼接結果        BiConsumer<String, String> concatenationPrinter = (str1, str2) -> System.out.println(str1 + str2);        concatenationPrinter.accept("Hello, ", "World!");    }}

8.BiPredicate 函數接口

BiPredicate接口用于表示接受兩個參數并返回一個布爾值的函數。它定義了一個名為test(T t, U u)的抽象方法,接受兩個參數,并返回一個布爾值。Qpc28資訊網——每日最新資訊28at.com

以下是BiPredicate接口的簡化版本:Qpc28資訊網——每日最新資訊28at.com

@FunctionalInterface public interface BiPredicate<T, U> {     boolean test(T t, U u);     // Default methods are defined also}

BiPredicate接口適用于那些需要對傳入的兩個參數進行某種條件判斷,并返回布爾值的情況。它可以用于執行各種條件判斷,如相等性比較、大小比較、復雜條件判斷等。Qpc28資訊網——每日最新資訊28at.com

下面是一個使用BiPredicate接口的示例:Qpc28資訊網——每日最新資訊28at.com

import java.util.function.BiPredicate;public class Main {    public static void main(String[] args) {        // 使用BiPredicate接口判斷兩個數是否相等        BiPredicate<Integer, Integer> equalityPredicate = (a, b) -> a.equals(b);        boolean isEqual = equalityPredicate.test(5, 5);        System.out.println(isEqual);  // 輸出: true        // 使用BiPredicate接口判斷一個字符串是否包含另一個字符串        BiPredicate<String, String> containsPredicate = (str1, str2) -> str1.contains(str2);        boolean isContains = containsPredicate.test("Hello, World!", "World");        System.out.println(isContains);  // 輸出: true    }}

本文鏈接:http://www.www897cc.com/showinfo-26-52164-0.htmlJava中的函數接口,你都用過了嗎

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 十個常見的 Kubernetes 陷阱和挑戰

下一篇: 事半功倍的十個Python內置函數

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 乌鲁木齐县| 遂宁市| 凭祥市| 五河县| 抚州市| 滁州市| 海盐县| 任丘市| 毕节市| 庆元县| 台山市| 洞头县| 腾冲县| 巴林右旗| 红河县| 讷河市| 伊吾县| 封开县| 屏山县| 威信县| 温泉县| 台东县| 五家渠市| 临漳县| 珲春市| 崇明县| 芦溪县| 阿坝县| 承德县| 法库县| 巫山县| 大姚县| 恩平市| 莲花县| 达拉特旗| 峨眉山市| 栖霞市| 马龙县| 铁力市| 漳州市| 平乐县|