常用的函数式接口之Supplier接口
Supplier
T get():获得结果
该方法不需要参数,它会按照某种实现逻辑(由Lambda表达式实现)返回一个数据
Supplier
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 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 sl) {
return sl.get();
}
}