Supplier<T>:包含一個無參的方法
T get():獲得結果
該方法不需要引數,它會按照某種實作邏輯(由Lambda運算式實作)回傳一個資料
Supplier<T>也被稱為生產型介面,如果我們指定了介面的泛型是什么型別,那么介面中的get方法就會生產什么型別的資料供我們使用
import java.util.function.Supplier;
?
public class SupplierDemo {
public static void main(String[] args) {
//呼叫 getInt方法
Integer i = getInt(() -> 123);//Lambda運算式簡寫版
System.out.println(i);
?
}
//定義一個方法,用來接收get回傳的資料
private static Integer getInt(Supplier<Integer> sl){
return sl.get();
}
}
練習:
定義一個類,提供getMax方法用于回傳一個陣列中的最大值并呼叫
package Demo0512;
?
import java.util.function.Supplier;
?
public class SupplierDemo01 {
public static void main(String[] args) {
//宣告一個陣列
int array[] = {12, 45, 4, 87, 546, 54};
//呼叫
int max1 = getMax(() -> {
int max = array[0];
for (int i = 0; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
}
}
return max;
});
System.out.println(max1);
}
private static int getMax(Supplier<Integer> sl) {
return sl.get();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/472918.html
標籤:其他
