案例一: Supplier接口获取最大值
需求: 定义一个类(SupplierTest),在类中提供两个方法
一个方法是:int getMax(Supplier<Integer> sup) 用于返回一个int数组中的最大值
一个方法是主方法,在主方法中调用getMax
package test.test103;
import java.util.function.Supplier;
/**
* 定义一个类(SupplierTest),在类中提供两个方法
* 一个方法是:int getMax(Supplier<Integer> sup) 用于返回一个int数组中的最大值
* 一个方法是主方法,在主方法中调用getMax
*/
public class SupplierTest {
public static void main(String[] args) {
// 定义一个int数组
int[] arr = {19, 50, 28, 37, 46};
int maxValue = getMax(() -> {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
});
System.out.println(maxValue);
}
// 用于返回一个int数组中的最大值
private static int getMax(Supplier<Integer> sup){
return sup.get();
}
}
案例二: Consumer接口按要求打印信息
需求: String[] strArray = {"张三,30","李四,35","王五,33"};
字符串数组中有多条信息,请按照格式: "姓名: XX,年龄: XX"的格式将信息打印出来
要求: 把打印姓名的动作作为第一个Consumer接口的Lambda实例
把打印年龄的动作作为 第二个Consumer接口的Lambda实例
将两个Consumer接口按照顺序组合到一起使用
package test;
import java.util.function.Consumer;
/**
* String[] strArray = {"张三,30","李四,35&