Supplier接口

目录

一、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());

}

 

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

        举例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接口

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值