Common function interface——Supplier interface

Supplier interface:

java.util.function.Supplier<T>接口仅包含一个无参的方法:T get()。用来获取一个泛型参数指定类型的对象数据。
Supplier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据

Use Cases:

public class Demo01Supplier {
    
    
    //定义一个方法,方法的参数传递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);
    }
}

Program demonstration:
Insert picture description here
Exercise: Find the maximum value of the array element:
Use the Supplier interface as the method parameter type, and use the Lambda expression to find the maximum value in the int array.
The generic type of the interface uses the java.lang.Integer class

Code:

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);
    }
}

Program demonstration:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/109137043