Supplier接口的使用
/*
* java.util.function.Supplier<T>接口仅包含一个无参的方法:T get(). 用来获取一个泛型参数指定类型的对象数据
* 定义一个方法,方法的参数传递Supplier<T>接口,泛型执行String,get方法返回一个String
* */
public class DemoSupplier {
public static String getSupplier(Supplier<String> supplier){
return supplier.get();
}
public static void main(String[] args) {
String str = getSupplier(()->"hello,Supplier");
System.out.println(str);
}
}
//定义一个方法,用于获取int类型数组中元素的最大值,方法的参数传递Supplier接口,泛型使用Integer
public class Test {
public static int getMax(Supplier<Integer> sup){
return sup.get();
}
public static void main(String[] args) {
int[] arr = {1,12,34,3,12,31,43,4};
int max = getMax(()->{
int M = 0;
for (int i:arr) {
if(i>M)
M=i;
}
return M;
});
System.out.println(max);
}
}