Java 常用函數式接口之Supplier接口


JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景,它們主要在 java.util.function 包中被提供。 下面是最簡單的Supplier接口及使用示例。

Supplier接口概述

// Supplier接口源碼


@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

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

import java.util.function.Supplier;

public class Demo01Supplier {
    public static void main(String[] args) {
        String msgA = "Hello ";
        String msgB = "World ";
        System.out.println(
                getString(
                        () -> msgA + msgB
                )
        );
    }

    private static String getString(Supplier<String> stringSupplier) {
        return stringSupplier.get();
    }
}

控制台輸出:

Hello World 

練習:求數組元素最大值

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

import java.util.function.Supplier;

public class DemoNumberMax {
    public static void main(String[] args) {
        int[] numbers = {100, 200, 300, 400, 500, -600, -700, -800, -900, -1000};
        int numberMax = arrayMax(
                () -> {
                    int max = numbers[0];
                    for (int number : numbers) {
                        if (max < number) {
                            max = number;
                        }
                    }
                    return max;
                }
        );
        System.out.println("數組中的最大值為:" + numberMax);
    }

    /**
     * 獲取一個泛型參數指定類型的對象數據
     * @param integerSupplier 方法的參數為Supplier,泛型使用Integer
     * @return 指定類型的對象數據
     */
    public static Integer arrayMax(Supplier<Integer> integerSupplier) {
        return integerSupplier.get();
    }
}

控制台輸出:

數組中的最大值為:500


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM