常见函数式接口
Supplier接口:
java.util.function.Supplier<T>接口仅包含一个无参的方法:T get()。用来获取一个泛型参数指定类型的对象数据。
Supplier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据
代码:
public class BSupplier {//定义一个方法,方法的参数传递Supplier<T>接口,泛型执行String,get方法就会返回一个Stringpublic static String getString(Supplier<String> sup){return sup.get();}public static void main(String[] args) {//调用getString方法,方法的参数Supplier<T>是一个函数式接口,所以可以传递Lambda表达式String s = getString(()->{//生成一个字符串并返回return "胡歌";});System.out.println(s);//优化Lambda表达式String s2 = getString(()->"赵丽颖");System.out.println(s2);} }
运行结果:
练习:求数组元素最大值
题目:
使用Supplier接口作为方法参数类型,通过Lambda表达式求出int数组中的最大值
提示:接口的泛型请使用java.lang.Integer类
代码:
public class BBSupplier2 {//定义一个方法,用于获取int类型数组中元素的最大值,方法的参数传递Supplier接口,泛型使用Integerpublic static int getMax(Supplier<Integer> supplier){return supplier.get();}public static void main(String[] args) {//定义一个int类型的数组,并赋值int[] arr = {100,2,3,4,50,60,-89,880};//调用getMax方法,方法的参数Supplier是一个函数式接口,所以可以传递Lambda表达式int maxValue = getMax(()->{//获取数组的最大值,并返回//定义一个变量,把数组中的第一个元素赋值给该变量,记录数组中int max = arr[0];for (int i : arr) {if (i>max){max=i;}}return max;});System.out.println("最大值的数据为:"+maxValue);} }