package tompeixun.demo05;
import java.util.Arrays;
import java.util.function.Supplier;
//通过Supplier<T>接口求数组最大值
public class Demo02 {
public static int getMax(Supplier<Integer> supplier) {
return supplier.get();
}
public static void main(String[] args) {
int[] array = {2, 5, 1, 6, 0};
int maxValue = getMax(new Supplier<Integer>() {
@Override
public Integer get() {
int max = array[0];//假设数组的第一个元素为最大值
//然后开始遍历数组,如果一个值大于max,则把该值赋给max
//这样循环一遍下来,max保存的就是数组中的最大值
for (int item : array
) {
if (item > max) {
max = item;
}
}
return max;
}
});
System.out.println(Arrays.toString(array));
System.out.println("匿名内部类求该数组最大值:" + maxValue);
int maxValue2 = getMax(() -> {
int max = array[0];//假设数组的第一个元素为最大值
//然后开始遍历数组,如果一个值大于max,则把该值赋给max
//这样循环一遍下来,max保存的就是数组中的最大值
for (int item : array
) {
if (item > max) {
max = item;
}
}
return max;
}
);