2020了你还不会Java8新特性?(六)Stream源码剖析 (3)

BaseStream 是所有流的父类 。

/** * Base interface for streams, which are sequences of elements supporting * sequential and parallel aggregate operations. The following example * illustrates an aggregate operation using the stream types {@link Stream} * and {@link IntStream}, computing the sum of the weights of the red widgets: * * <pre>{@code * int sum = widgets.stream() * .filter(w -> w.getColor() == RED) * .mapToInt(w -> w.getWeight()) * .sum(); * }</pre> * * See the class documentation for {@link Stream} and the package documentation * for <a href="http://www.likecs.com/package-summary.html">java.util.stream</a> for additional * specification of streams, stream operations, stream pipelines, and * parallelism, which governs the behavior of all stream types. * * @param <T> the type of the stream elements * @param <S> the type of of the stream implementing {@code BaseStream} * @since 1.8 * @see Stream * @see IntStream * @see LongStream * @see DoubleStream * @see <a href="http://www.likecs.com/package-summary.html">java.util.stream</a> */ public interface BaseStream<T, S extends BaseStream<T, S>> extends AutoCloseable public interface Stream<T> extends BaseStream<T, Stream<T>> BaseStream(){ Iterator<T> iterator(); 迭代器 Spliterator<T> spliterator(); 分割迭代器 。 这是一个流的终止操作。 boolean isParallel(); 是否是并行。 S sequential(); // 返回一个等价的串行流。 返回S是一个新的流对象 S parallel(); //返回一个并行流。 S unordered(); // 返回一个无序的流。 S onClose(Runnable closeHandler); //当前流.onClose、 当close调用时,调用此方法。 void close(); // 关闭流 } 关闭处理器的举例 /** * 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); public static void main(String[] args) { List<String> list = Arrays.asList("hello","world"); NullPointerException nullPointerException = new NullPointerException("myexception"); try (Stream<String> stream = list.stream()){ stream.onClose(()->{ System.out.println("aaa"); // throw new NullPointerException("first"); throw nullPointerException; }).onClose(()->{ System.out.println("aaa"); throw nullPointerException; }).forEach(System.out::println); } // 出现异常会被压制, // 如果是同一个异常对象,只会打印一次异常。 如果是多个异常对象。都会被打印。 }

javadoc 中的介绍比任何资料都详细。

Stream 源码分析。 stream(); /** * Returns a sequential {@code Stream} with this collection as its source. 返回一个串行流,把这个集合当做源 * <p>This method should be overridden when the {@link #spliterator()} * method cannot return a spliterator that is {@code IMMUTABLE}, * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()} * for details.) 当不能返回 三种方法 中的一个时,这个方法应该被重写。 * @implSpec * The default implementation creates a sequential {@code Stream} from the * collection's {@code Spliterator}. 默认会从集合中创建一个串行流。 返回 * @return a sequential {@code Stream} over the elements in this collection * @since 1.8 */ default Stream<E> stream() { return StreamSupport.stream(spliterator(), false); } spliterator(); 分割迭代器 /** * Creates a {@link Spliterator} over the elements in this collection. * * Implementations should document characteristic values reported by the * spliterator. Such characteristic values are not required to be reported * if the spliterator reports {@link Spliterator#SIZED} and this collection * contains no elements. * <p>The default implementation should be overridden by subclasses that * can return a more efficient spliterator. In order to * preserve expected laziness behavior for the {@link #stream()} and * {@link #parallelStream()}} methods, spliterators should either have the * characteristic of {@code IMMUTABLE} or {@code CONCURRENT}, or be * <em><a href="Spliterator.html#binding">late-binding</a></em>. 默认的子类应该被重写。为了保留parallelStream 和 stream的延迟行为。特性需要满足IMMUTABLE 或者CONCURRENT * If none of these is practical, the overriding class should describe the * spliterator's documented policy of binding and structural interference, * and should override the {@link #stream()} and {@link #parallelStream()} * methods to create streams using a {@code Supplier} of the spliterator, * as in: * <pre>{@code * Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics) * }</pre> 为什么叫分割迭代器。先分割,在迭代。 如果不能满足上述的要求,则重写的时候应该满足上述的需求、 * <p>These requirements ensure that streams produced by the * {@link #stream()} and {@link #parallelStream()} methods will reflect the * contents of the collection as of initiation of the terminal stream * operation. 这些确保了流会返回的内容。 * @implSpec * The default implementation creates a * <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator * from the collections's {@code Iterator}. The spliterator inherits the * <em>fail-fast</em> properties of the collection's iterator. * <p> * The created {@code Spliterator} reports {@link Spliterator#SIZED}. 默认会从集合的迭代器中创建出一个延迟的分割迭代器。 默认的迭代器 会有默认大小的迭代器。 * @implNote * The created {@code Spliterator} additionally reports * {@link Spliterator#SUBSIZED}. * * <p>If a spliterator covers no elements then the reporting of additional * characteristic values, beyond that of {@code SIZED} and {@code SUBSIZED}, * does not aid clients to control, specialize or simplify computation. * However, this does enable shared use of an immutable and empty * spliterator instance (see {@link Spliterators#emptySpliterator()}) for * empty collections, and enables clients to determine if such a spliterator * covers no elements. 如果分割迭代器不包含任何元素。 其他的属性对客户端是没有任何帮助的。 然而会促进分割迭代器共享的作用。 * @return a {@code Spliterator} over the elements in this collection * @since 1.8 */ @Override default Spliterator<E> spliterator() { return Spliterators.spliterator(this, 0); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgfxs.html