Stream接口通过一些方法来证明自身价值

再来看一下Stream的接口声明:


  1. public interface Stream<T> extends BaseStream<T, Stream<T>>  

参考上面的解释这里不难理解:即Stream<T>可以继续拆分为Stream<T>,我们可以通过它的一些方法来证实: 


  1. Stream<T> filter(Predicate<? super T> predicate);  
  2.     <R> Stream<R> map(Function<? super T, ? extends R> mapper);  
  3.     <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);  
  4.     Stream<T> sorted();  
  5.     Stream<T> peek(Consumer<? super T> action);  
  6.     Stream<T> limit(long maxSize);  
  7.     Stream<T> skip(long n);  
  8.     … 

这些都是操作流的中间操作,它们的返回结果必须是流对象本身。

关闭流操作

BaseStream 实现了 AutoCloseable 接口,也就是 close() 方法会在流关闭时被调用。同时,BaseStream 中还给我们提供了onClose()方法:


  1. /** * Returns an equivalent stream with an additional close handler. Close * handlers are run when the {@link #close()} method * is called on the stream, and are executed in the order they were * added. All close handlers are run, even if earlier close handlers throw * exceptions. If any close handler throws an exception, the first * exception thrown will be relayed to the caller of {@code close()}, with * any remaining exceptions added to that exception as suppressed exceptions * (unless one of the remaining exceptions is the same exception as the * first exception, since an exception cannot suppress itself.) May * return itself. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param closeHandler A task to execute when the stream is closed * @return a stream with a handler that is run if the stream is closed */ 
  2. S onClose(Runnable closeHandler); 

当AutoCloseable的close()接口被调用的时候会触发调用流对象的onClose()方法,但有几点需要注意:

  •  onClose() 方法会返回流对象本身,也就是说可以对改对象进行多次调用
  •  如果调用了多个onClose() 方法,它会按照调用的顺序触发,但是如果某个方法有异常则只会向上抛出第一个异常
  •  前一个 onClose() 方法抛出了异常不会影响后续 onClose() 方法的使用
  •  如果多个 onClose() 方法都抛出异常,只展示第一个异常的堆栈,而其他异常会被压缩,只展示部分信息
【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章