Java8 函数式接口之 Supplier

431 阅读1分钟

Supplier 是什么

  • 可以理解为就是一个容器,调用 supplier.get()方法就能获取容器中的值,示例代码如下

    @Test
      public void test2(){
      
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
        Supplier<LocalDateTime> s = () -> LocalDateTime.now();
        LocalDateTime time = s.get();
    
        System.out.println(time);
    
        Supplier<String> s1 = () -> dtf.format(LocalDateTime.now());
        String time2 = s1.get();
    
        System.out.println(time2);
    
      }
    
  • supplier 中还扩展 了其他的接口实现例如 IntSupplier 、DoubleSupplier 、LongSupplier 、BooleanSupplier 使用跟 Supplier 无其他差别

  • 使用场景 2 就是配合其他方法使用例如下面的代码

    @Test
      public void test_Supplier2() {
    
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 4);
        //返回一个optional对象
        Optional<Integer> first = stream.filter(i -> i > 4)
                .findFirst();
    
        //optional对象有需要Supplier接口的方法
        //orElse,如果first中存在数,就返回这个数,如果不存在,就放回传入的数
        System.out.println(first.orElse(1));
        System.out.println(first.orElse(7));
    
        System.out.println("********************");
    
        Supplier<Integer> supplier = ()->1;
        System.out.println(supplier.get());
    
        //orElseGet,如果first中存在数,就返回这个数,如果不存在,就返回supplier返回的值
        System.out.println(first.orElseGet(supplier));
      }
    
  • 源码如下

    // 接口很简单就只有一个 get()方法,用于返回 T 对象
    
    @FunctionalInterface
    public interface Supplier<T> {
    
        /**
         * Gets a result.
         *
         * @return a result
         */
        T get();
    }
    

小结

  • supplier 就是一个容器,用来存储数据的

  • 通常函数描述符为 () -> T

  • 具有延迟创建的特点,只有在使用到的时候才会去执行里面的逻辑