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();
}
}