Java Reference
In-Depth Information
A data source is said to have an encounter order if the order in which the elements are traversed by an iterator is
predictable and meaningful. For example, arrays and lists always have an encounter order that is from the element at
index 0 to the element at the last index. All ordered data sources have an encounter order for their elements. Streams
based on data sources having an encounter order also have an encounter order for their elements. Sometimes a
stream operation may impose an encounter order on an otherwise unordered stream. For example, a HashSet does
not have an encounter order for its elements. However, applying a sort operation on a stream based on a HashSet
imposes an encounter order so that elements are yielded in sorted order.
Streams Are Not Reusable
Unlike collections, streams are not reusable. They are one-shot objects. A stream cannot be reused after calling a
terminal operation on it. If you need to perform a computation on the same elements from the same data source
again, you must recreate the stream pipeline. A stream implementation may throw an IllegalStateException if it
detects that the stream is being reused.
Architecture of the Streams API
Figure 13-6 shows a class diagram for the stream-related interfaces. Stream-related interfaces and classes are in the
java.util.stream package.
Figure 13-6. A class diagram for stream-related interfaces in the Streams API
All stream interfaces inherit from the BaseStream interface, which inherits from the AutoCloseable interface
from the java.lang package. In practice, most streams use collections as their data source, and collections do not
need to be closed. When a stream is based on a closeable data source such as a file I/O channel, you may create the
instance of the stream using a try-with-resources statement to get it closed automatically. Methods common to all
types of streams are declared in the BaseStream interface.
Iterator<T> iterator() : It returns an iterator for the stream. You will almost never need
to use this method in your code. This is a terminal operation. After calling this method, you
cannot call any other methods on the stream.
S sequential() : It returns a sequential stream. If the stream is already sequential, it returns
itself. Use this method to convert a parallel stream into a sequential stream. This is an
intermediate operation.
S parallel() : It returns a parallel stream. If the stream is already parallel, it returns itself.
Use this method to convert a parallel stream into a sequential stream. This is an intermediate
operation.
 
Search WWH ::




Custom Search