常用的函数式接口_supplier接口-接口练习
常用的函数式接口_supplier接口
常用的函数式接口
java.util.function.SuppLier<T>接口仅包含一个无参的方法:T get()。用来获取一个泛型参数指定类型的对象数据。
SuppLier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据
接口练习
题目
使用Suppier接口作为方法参数类型,通过Lambda表达式求出int数组中的最大值.提示:接口的泛型请使用java.lang.Integer类
package A_Lian_one.Demo22.Demo04Supplier; import java.util.function.Supplier; public class Demo02Test { public static void main(String[] args) { //定义一个int类型的数组,并赋值 int[] arr ={100,0,-50,88,99,33,-30}; Integer maxValue = getMax(() -> { //获取数组的最大值,并返回 //定义一个变量,把数组中的第一个元素赋值给变量,记录数组中元素的最大值 int max = arr[0]; for (int i : arr) { if (i > max) { //如果i大于max max = i; } } return max; }); System.out.println("数组中元素的最大值"+maxValue); } public static Integer getMax(Supplier<Integer> sup) { return sup.get(); } }