再来看一下Stream的接口声明:
- public interface Stream<T> extends BaseStream<T, Stream<T>>
参考上面的解释这里不难理解:即Stream<T>可以继续拆分为Stream<T>,我们可以通过它的一些方法来证实:
- Stream<T> filter(Predicate<? super T> predicate);
- <R> Stream<R> map(Function<? super T, ? extends R> mapper);
- <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
- Stream<T> sorted();
- Stream<T> peek(Consumer<? super T> action);
- Stream<T> limit(long maxSize);
- Stream<T> skip(long n);
- …
这些都是操作流的中间操作,它们的返回结果必须是流对象本身。
关闭流操作
BaseStream 实现了 AutoCloseable 接口,也就是 close() 方法会在流关闭时被调用。同时,BaseStream 中还给我们提供了onClose()方法:
- /** * 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 */
- S onClose(Runnable closeHandler);
当AutoCloseable的close()接口被调用的时候会触发调用流对象的onClose()方法,但有几点需要注意:
- onClose() 方法会返回流对象本身,也就是说可以对改对象进行多次调用
- 如果调用了多个onClose() 方法,它会按照调用的顺序触发,但是如果某个方法有异常则只会向上抛出第一个异常
- 前一个 onClose() 方法抛出了异常不会影响后续 onClose() 方法的使用
- 如果多个 onClose() 方法都抛出异常,只展示第一个异常的堆栈,而其他异常会被压缩,只展示部分信息