Danny Yu Sun's Blog

Brain-dumping.

Java Stream API

Java 8引入了Stream的概念,掌握这个概念的最佳方式是阅读Java官方文档。 可以浏览一下Oracle Java文档或是Android官方文档

有些关键的概念需要掌握:stream、source、stream pipeline、stream operations、intermediate operations、terminal operation。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * 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);
}

Stream实例只能被使用一次,否则会抛出Runtime Exception:

1
java.lang.IllegalStateException: stream has already been operated upon or closed

The right and most convenient way to use streams are by a stream pipeline, which is a chain of stream source, intermediate operations, and a terminal operation.