425Suppler接口和426Suppler接口练习
常用的函数式接口-Supplier接口
/*
常用的函数式接口
java.util.function.Supplier<T>接口仅包含一个无参的方法:T get()。用来获取一个泛型参数指定类型的对象数据。
Supplier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据
*/
public class DemoSupplier {
//定义一个方法,方法的参数传递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);
//优化
String s1 = getString(() -> "朱雀志");
System.out.println(s1);
}
}
public class Demo {
private static String getString(Supplier<String> function) {
return function.get();
}
public static void main(String[] args) {
String msgA = "Hello ";
String msgB = "World";
System.out.println(getString(() -> msgA + msgB));
}
}
//控制台输出 Hello World
练习Supplier接口-求数组元素最大值
public class Demo02Test {
//定义一个方法,用于获取int类型数组中元素的最大值,方法的参数传递Supplier接口,泛型使用Integer
public static int getMax(Supplier<Integer> sup){
return sup.get();
}
public static void main(String[] args) {
//定义一个int类型的数组并赋值
int arr[] = {100,23,456,-23,-90,0,-678,14};
//调用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);
}
}

浙公网安备 33010602011771号