常用的函数式接口—Supplier接口以及练习
常用的函数式接口—Supplier接口
java.util.function.Supplier<T>接口仅包含一个无参的方法:
T get() 用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,
这也就意味着对应的Lambda表达式需要对外提供一个符合泛型类型的对象数据
Supplier接口被称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据
定义一个方法,方法的参数传递Supplier<T>接口,泛型指定String,get方法就会返回一个String
//定义一个方法,方法的参数传递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接口练习——求数组元素最大值
使用Supplier接口作为方法参数类型,通过Lambda表达式求出int数组中的最大值。
public class SupplierTest { //定义一个方法,用于获取int类型数组元素的最大值,方法的参数传递Supplier接口,泛型使用Integer public static int getMax(Supplier<Integer> sup){ return sup.get(); } public static void main(String[] args) { //定义一个int类型的数组并返回 int[] arr = {45,12,93,56,10,89}; //调用getMax方法,方法的参数Supplier是一个函数式接口,所以可以传递Lambda表达式 int maxValue = getMax(()->{ //获取数组的最大值,并返回 //定义一个变量,把数组中的第一个元素赋值给该变量,记录数组元素的最大值 int max = arr[0]; for (int i : arr) { //使用其他元素和最大值比较 if (i>max){ // 如果i>max,则替换max为最大值 max = i; } } //返回最大值 return max; }); System.out.println("数组中元素的最大值:"+maxValue); } }
运行结果:


浙公网安备 33010602011771号