| ① Supplier接口分析 Supplier<Integer> supplier = new Supplier<Integer>() {  @Override  public Integer get() {  //返回一个随机值  return new Random().nextInt();  }  }; 
 看一下这段代码,我们通过创建一个 Supplier 对象,实现了一个 get 方法,这个方法无参数,返回一个值;所以,每次使用这个接口的时候都会返回一个值,并且保存在这个接口中,所以说是一个容器。 ② lambda表达式作为 Supplier //② 使用lambda表达式,  supplier = () -> new Random().nextInt();  System.out.println(supplier.get());  System.out.println("********************"); 
 上面的这段代码,我们使用 lambda 表达式返回一个 Supplier类型的接口,然后,我们调用 get 方法就可以获取这个值了。 ③ 方法引用作为 Supplier //③ 使用方法引用  Supplier<Double> supplier2 = Math::random;  System.out.println(supplier2.get()); 复制代码 
 方法引用也是返回一个Supplier类型的接口。 2.3 Supplier 实例2 我们看完第一个实例之后,我们应该有一个了解了,下面再看一个。 /**  * Supplier接口测试2,使用需要Supplier的接口方法  */  @Test  public void test_Supplier2() {  Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);  //返回一个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 = new Supplier<Integer>() {  @Override  public Integer get() {  //返回一个随机值  return new Random().nextInt();  }  };  //orElseGet,如果first中存在数,就返回这个数,如果不存在,就返回supplier返回的值  System.out.println(first.orElseGet(supplier));  } 
 输出结果   代码分析 Optional<Integer> first = stream.filter(i -> i > 4)  .findFirst(); 
 使用这个方法获取到一个 Optional 对象,然后,在 Optional 对象中有 orElse 方法 和 orElseGet 是需要一个 Supplier 接口的。 //optional对象有需要Supplier接口的方法  //orElse,如果first中存在数,就返回这个数,如果不存在,就放回传入的数  System.out.println(first.orElse(1));  System.out.println(first.orElse(7));  System.out.println("********************");  Supplier<Integer> supplier = new Supplier<Integer>() {  @Override  public Integer get() {  //返回一个随机值  return new Random().nextInt();  }  };  //orElseGet,如果first中存在数,就返回这个数,如果不存在,就返回supplier返回的值  System.out.println(first.orElseGet(supplier)); 
 
    orElse:如果first中存在数,就返回这个数,如果不存在,就放回传入的数orElseGet:如果first中存在数,就返回这个数,如果不存在,就返回supplier返回的值 2.4 其他 Supplier 接口 除了上面使用的 Supplier 接口,还可以使用下面这些 Supplier 接口。 IntSupplier 、DoubleSupplier 、LongSupplier 、BooleanSupplier,使用方法和上面一样。 2.5 Supplier 总结 ① Supplier 接口可以理解为一个容器,用于装数据的。 ② Supplier 接口有一个 get 方法,可以返回值。 3 Predicate 接口 Predicate 接口是一个谓词型接口,其实,这个就是一个类似于 bool 类型的判断的接口,后面看看就明白了。 (编辑:南平站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |