函数式接口-常见函数式接口-Supplier接口
常见函数式接口
JDK提供了大量常用的函数式接口以丰富Lambda的经典使用常见 它们注意在java.util.function包中被提供
Supplier接口
Supplier<T>接口仅包含一个无参的方法:T get() 用来获取一个泛型参数指定类型的UI对象数据 由于这是一个函数式接口 这也意味着对应的Lambda表达式需要对外提供 一个符合泛型类型的对象数据
Supplier<T>接口被称之为生产型接口 指定接口的泛型是什么类型 那么接口中的get方法就会生产什么类型的数据
代码:
//定义一个方法 方法的参数传递Supplier<T>接口 泛型执行String get方法就会返回一个String
public static String getString(Supplier<String> sup){
return sup.get();
}
public static void main(String[] args) {
//调用getString方法的参数Supplier是一个函数式接口 所以可以传递Lambda表达式
String s=getString(()->{
return "胡歌";
});
System.out.println(s);
//优化Lambda
String s1=getString(()->"张三");
System.out.println(s1);
}
运行结果:

练习:求数组元素最大值
题目:
使用Supplier接口作为方法参数类型 通过Lambda表达式求出int数组中的最大值 提示:接口的泛型请使用java.lang.Integer类
代码:
public class Demo02Supplier {
//定义一个方法 方法的参数传递Supplier<T>接口 泛型执行int get方法就会返回一个int
public static Integer getInteger(Supplier<Integer> sup){
return sup.get();
}
public static void main(String[] args) {
int[] arr={10,20,50,30,40};
//调用getInteger方法的参数Supplier是一个函数式接口 所以可以传递Lambda表达式
Integer maxArr = getInteger(() -> {
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
});
System.out.println(maxArr);
}
}
运行结果:


浙公网安备 33010602011771号