02 函数式编程接口Supplier

“函数式编程是种编程方式,它将电脑运算视为函数的计算。函数编程语言最重要的基础是λ演算(lambda calculus),而且λ演算的函数可以接受函数当作输入(参数)和输出(返回值)”。它提供了四个基础的接口:Supplier 、Function 、Consumer 、Predicate。这一节我们看一下Supplier的用法。

  • Supplier < T >: 数据提供器,可以提供 T 类型对象;无参的构造器,提供了 get 方法,以下是Supplier的源代码:
package java.util.function;

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
  • 返回一个字符串
Supplier<String> stringSupplier = new Supplier<String>() {
    @Override
    public String get() {
        return "zhangli";
    }
};
继续使用lambda表达式优化:
Supplier<String> stringSupplier = () -> "zhangli";
System.out.println(stringSupplier.get());
  • 返回当前时间
Supplier<LocalDateTime> localDateTimeSupplier = () -> LocalDateTime.now();
System.out.println(localDateTimeSupplier.get());
  • 创建一个对象
class Student {

    public static void main(String args[]){
        //这句话显然应该放到其他地方测试
        Student student = Student.create(Student::new);
    }

    public static Student create(final Supplier<Student> supplier) {
        return supplier.get();
    }

    String name;

    public Student() {
    }

    public Student(String name) {
        this.name = name;
    }
}

以上就是Supplier的基本使用。

posted @ 2020-04-03 14:34  张力的程序园  阅读(524)  评论(0)    收藏  举报