Supplier接口

Supplier接口目录一 Supplier 接口源码二 Supplier 示例三 其他 Supplier 接口一 Supplier 接口源码 publicinterf T Getsaresult returnaresul Tget Supplier 接口是一个供给型的接口 本质就是一个容器 可以用来存储数据 或者是产生数据的规则 然后可以供其 T

目录

一、Supplier接口源码

二、Supplier示例

三、其他Supplier接口

一、Supplier接口源码

public interface Supplier<T> { / * Gets a result. * * @return a result */ T get(); }

        Supplier接口是一个供给型的接口,本质就是一个容器,可以用来存储数据(或者是产生数据的规则),然后可以供其他方法使用的这么一个接口。

二、Supplier示例

        举例1:随机数获取

        例子中定义了返回100以内随机数的Supplier对象,每次想获取随机数时,就调用Supplier对象的get方法即可。在这个示例中,Supplier.get()等价于new Random().nextInt(100),只是看起来更简单。

public static void main(String[] args) { Supplier<Integer> supplier = new Supplier<Integer>() { @Override public Integer get() { return new Random().nextInt(100); } }; System.out.println(supplier.get()); System.out.println(supplier.get()); System.out.println(supplier.get()); }

Supplier接口 

          举例2:Supplier搭配Optional

          例子中,找到指定list中第一个小于100的数,没有的话就随机返回一个小于100的数。

 public static void main(String[] args) { Supplier<Integer> supplier = new Supplier<Integer>() { @Override public Integer get() { return new Random().nextInt(100); } }; List<Integer> integers = List.of(1000, 2000, 3000); Optional<Integer> optionalInteger = integers.stream().filter(val -> val < 100).findFirst(); Integer integer = optionalInteger.orElse(supplier.get()); System.out.println(integer); }

Supplier接口

        举例3:Supplier创建对象

        例子中,我们先定义了一个静态内部类Student,然后创建了一个Supplier来创建Student对象,看输出结果可知,每次调用Supplier.get方法时,都会创建一个新的Student对象(hashCode值不同)。

 static class Student { Student() { System.out.println("student init"); System.out.println("hashCode: " + hashCode()); } } public static void main(String[] args) { Supplier<Student> supplier = Student::new; System.out.println(supplier.get()); System.out.println(supplier.get()); System.out.println(supplier.get()); System.out.println(supplier.get()); System.out.println(supplier.get()); }

Supplier接口 

 

三、其他Supplier接口

        JDK里面提供了其他返回类型数据的Supplier:IntSupplier 、DoubleSupplier 、LongSupplier 、BooleanSupplier等。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233923.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号