Supplier interface of commonly used functional interface in Java

>>> JDK provides a large number of commonly used functional interfaces to enrich the typical usage scenarios of Lambda, and they are mainly provided in the java.util.function package. This article is the simplest Supplier interface and usage examples.

 

overview

// Supplier接口源码


@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

The java.util.function.Supplier interface contains only one method with no arguments: T get() . Used to get object data of the type specified by a generic parameter. Since this is a functional interface, this means that the corresponding Lambda expression needs to "provide" an object data conforming to the generic type. like:

import java.util.function.Supplier;

public class Demo01Supplier {
    public static void main(String[] args) {
        String msgA = "Hello ";
        String msgB = "World ";
        System.out.println(
                getString(
                        () -> msgA + msgB
                )
        );
    }

    private static String getString(Supplier<String> stringSupplier) {
        return stringSupplier.get();
    }
}

Console output:

Hello World 

Exercise: Find the maximum value of an array element

Use the Supplier interface as the method parameter type, and find the maximum value in the int array through the Lambda expression. The generic type of the interface uses the java.lang.Integer class.

import java.util.function.Supplier;

public class DemoNumberMax {
    public static void main(String[] args) {
        int[] numbers = {100, 200, 300, 400, 500, -600, -700, -800, -900, -1000};
        int numberMax = arrayMax(
                () -> {
                    int max = numbers[0];
                    for (int number : numbers) {
                        if (max < number) {
                            max = number;
                        }
                    }
                    return max;
                }
        );
        System.out.println("数组中的最大值为:" + numberMax);
    }

    /**
     * 获取一个泛型参数指定类型的对象数据
     * @param integerSupplier 方法的参数为Supplier,泛型使用Integer
     * @return 指定类型的对象数据
     */
    public static Integer arrayMax(Supplier<Integer> integerSupplier) {
        return integerSupplier.get();
    }
}

Console output:

数组中的最大值为:500

Guess you like

Origin blog.csdn.net/Xuange_Aha/article/details/130660955