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
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