目录
一、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等。