Supplier系列接口最大的特点是他不需要参数,但可以返回一个值。Supplier系列的接口共有5个,如下:
目录
java.util.function.Supplier<T> 接口仅包含一个无参的方法: T get() 。用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
-
Supplier
返回一个任意类型的值。看一下示例代码:public class TestSupplier { public static void main(String[] args) { // 获取当前时间戳 test1(System::currentTimeMillis); // 将两个字符串转换成大写 test2(("test" + " supplier")::toUpperCase); // 找出整形数组中最大的数 int[] arr = {3, 7, 1, 0, 8, 5}; test3(() -> { Arrays.sort(arr); return arr[arr.length - 1]; }); } public static void test1(Supplier<Long> supplier) { Long s = supplier.get(); System.out.println(s); } public static void test2(Supplier<String> supplier) { String s = supplier.get(); System.out.println(s); } public static void test3(Supplier<Integer> supplier) { Integer s = supplier.get(); System.out.println(s); } }
像上面的示例中
public static native long currentTimeMillis(); 和
public String toUpperCase() { return toUpperCase(Locale.getDefault()); }
方法都是不需要参数而直接返回结果的,因此可以使用Supplier。
输出结果如下:
1608520763764 TEST SUPPLIER 8
-
IntSupplier
IntSupplier返回的结果只能是Int类型的。@FunctionalInterface public interface IntSupplier { /** * Gets a result. * * @return a result */ int getAsInt(); }
示例代码如下:
public class TestIntSupplier { public static void main(String[] args) { test(() -> 111); // 直接返回111 test("test IntSupplier"::length); // 返回字符串的长度 } public static void test(IntSupplier supplier) { int asInt = supplier.getAsInt(); System.out.println(asInt); } }
-
LongSupplier
用法同IntSupplier一样,返回的是Long类型。 -
DoubleSupplier
用法同IntSupplier一样,返回的是Double类型。 -
BooleanSupplier
用法同IntSupplier一样,返回的是Boolean类型。