Stream
and IntStream
:
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
In this example, widgets
is a Collection<Widget>
. We create
a stream of Widget
objects via Collection.stream()
,
filter it to produce a stream containing only the red widgets, and then
transform it into a stream of int
values representing the weight of
each red widget. Then this stream is summed to produce a total weight.
In addition to Stream
, which is a stream of object references,
there are primitive specializations for IntStream
, LongStream
,
and DoubleStream
, all of which are referred to as "streams" and
conform to the characteristics and restrictions described here.
To perform a computation, stream
operations are composed into a
stream pipeline. A stream pipeline consists of a source (which
might be an array, a collection, a generator function, an I/O channel,
etc), zero or more intermediate operations (which transform a
stream into another stream, such as Stream#filter(Predicate)
), and a
terminal operation (which produces a result or side-effect, such
as Stream#count()
or Stream#forEach(Consumer)
).
Streams are lazy; computation on the source data is only performed when the
terminal operation is initiated, and source elements are consumed only
as needed.
A stream implementation is permitted significant latitude in optimizing
the computation of the result. For example, a stream implementation is free
to elide operations (or entire stages) from a stream pipeline -- and
therefore elide invocation of behavioral parameters -- if it can prove that
it would not affect the result of the computation. This means that
side-effects of behavioral parameters may not always be executed and should
not be relied upon, unless otherwise specified (such as by the terminal
operations forEach
and forEachOrdered
). (For a specific
example of such an optimization, see the API note documented on the
count
operation. For more detail, see the
side-effects section of the
stream package documentation.)
Collections and streams, while bearing some superficial similarities,
have different goals. Collections are primarily concerned with the efficient
management of, and access to, their elements. By contrast, streams do not
provide a means to directly access or manipulate their elements, and are
instead concerned with declaratively describing their source and the
computational operations which will be performed in aggregate on that source.
However, if the provided stream operations do not offer the desired
functionality, the iterator()
and spliterator()
operations
can be used to perform a controlled traversal.
A stream pipeline, like the "widgets" example above, can be viewed as
a query on the stream source. Unless the source was explicitly
designed for concurrent modification (such as a ConcurrentHashMap
),
unpredictable or erroneous behavior may result from modifying the stream
source while it is being queried.
Most stream operations accept parameters that describe user-specified
behavior, such as the lambda expression w -> w.getWeight()
passed to
mapToInt
in the example above. To preserve correct behavior,
these behavioral parameters:
Such parameters are always instances of a
functional interface such
as java.
, and are often lambda expressions or
method references. Unless otherwise specified these parameters must be
non-null.
A stream should be operated on (invoking an intermediate or terminal stream
operation) only once. This rules out, for example, "forked" streams, where
the same source feeds two or more pipelines, or multiple traversals of the
same stream. A stream implementation may throw IllegalStateException
if it detects that the stream is being reused. However, since some stream
operations may return their receiver rather than a new stream object, it may
not be possible to detect reuse in all cases.
Streams have a close()
method and implement AutoCloseable
.
Operating on a stream after it has been closed will throw IllegalStateException
.
Most stream instances do not actually need to be closed after use, as they
are backed by collections, arrays, or generating functions, which require no
special resource management. Generally, only streams whose source is an IO channel,
such as those returned by Files#lines(Path)
, will require closing. If a
stream does require closing, it must be opened as a resource within a try-with-resources
statement or similar control structure to ensure that it is closed promptly after its
operations have completed.
Stream pipelines may execute either sequentially or in
parallel. This
execution mode is a property of the stream. Streams are created
with an initial choice of sequential or parallel execution. (For example,
Collection.
creates a sequential stream,
and Collection.
creates
a parallel one.) This choice of execution mode may be modified by the
sequential()
or parallel()
methods, and may be queried with
the isParallel()
method.
IntStream
, LongStream
, DoubleStream
, java.util.stream
Modifier and Type | Class and Description |
---|---|
public static interface |
Modifier and Type | Method and Description |
---|---|
public boolean | Returns: true if either all elements of the stream match the
provided predicate or the stream is empty, otherwise false a non-interfering,
stateless
predicate to apply to elements of this stream predicate)Returns whether all elements of this stream match the provided predicate. |
public boolean | Returns: true if any elements of the stream match the provided
predicate, otherwise false a non-interfering,
stateless
predicate to apply to elements of this stream predicate)Returns whether any elements of this stream match the provided predicate. |
public static < type of elements T> Stream. | |
public < the type of the mutable result container R> R | Returns: the result of the reductiona function that creates a new mutable result container.
For a parallel execution, this function may be called
multiple times and must return a fresh value each time. supplier, BiConsumer<R, ? super T> an associative,
non-interfering,
stateless
function that must fold an element into a result
container. accumulator, BiConsumer<R, R> an associative,
non-interfering,
stateless
function that accepts two partial result containers
and merges them, which must be compatible with the
accumulator function. The combiner function must fold
the elements from the second result container into the
first result container. combiner)Performs a mutable reduction operation on the elements of this stream. |
public < the type of the result R, the intermediate accumulation type of the A> RCollector | Returns: the result of the reductionthe collector)Collector describing the reductionPerforms a mutable
reduction operation on the elements of this stream using a
|
public static < The type of stream elements T> Stream | |
public long | |
public Stream | Returns: the new streamReturns a stream consisting of the distinct elements (according to
|
public default Stream | Returns: the new streama non-interfering,
stateless
predicate to apply to elements to determine the longest
prefix of elements. predicate)Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. |
public static < the type of stream elements T> Stream | |
public Stream | Returns: the new streama non-interfering,
stateless
predicate to apply to each element to determine if it
should be included predicate)Returns a stream consisting of the elements of this stream that match the given predicate. |
public Optional | |
public Optional | |
public < The element type of the new stream R> Stream | Returns: the new streama non-interfering,
stateless
function to apply to each element which produces a stream
of new values mapper)Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. |
public DoubleStream | Returns: the new streama non-interfering,
stateless
function to apply to each element which produces a stream
of new values mapper)Returns an |
public IntStream | Returns: the new streama non-interfering,
stateless
function to apply to each element which produces a stream
of new values mapper)Returns an |
public LongStream | Returns: the new streama non-interfering,
stateless
function to apply to each element which produces a stream
of new values mapper)Returns an |
public void | forEach(Consumer<? super T>
a
non-interfering action to perform on the elements action)Performs an action for each element of this stream. |
public void | forEachOrdered(Consumer<? super T>
a
non-interfering action to perform on the elements action)Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. |
public default < The element type of the new stream R> Stream | Returns: the new streama gatherer gatherer)
Preview
Second Preview of Stream Gatherers (JEP 473).
Returns a stream consisting of the results of applying the given
|
public static < the type of stream elements T> Stream | |
public static < the type of stream elements T> Stream | Returns: a new sequentialStream the initial element seed, final UnaryOperator<T> a function to be applied to the previous element to produce
a new element f)Returns an infinite sequential ordered The first element (position |
public static < the type of stream elements T> Stream | Returns: a new sequentialStream the initial element seed, Predicate<? super T> a predicate to apply to elements to determine when the
stream must terminate. hasNext, UnaryOperator<T> a function to be applied to the previous element to produce
a new element next)Returns a sequential ordered |
public Stream | Returns: the new streamthe number of elements the stream should be limited to maxSize)Returns a stream consisting of the elements of this stream, truncated
to be no longer than |
public < The element type of the new stream R> Stream | Returns: the new streama non-interfering,
stateless
function to apply to each element mapper)Returns a stream consisting of the results of applying the given function to the elements of this stream. |
public default < The element type of the new stream R> Stream | Returns: the new streama non-interfering,
stateless
function that generates replacement elements mapper)Returns a stream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements. |
public default DoubleStream | Returns: the new streama non-interfering,
stateless
function that generates replacement elements mapper)Returns a |
public default IntStream | Returns: the new streama non-interfering,
stateless
function that generates replacement elements mapper)Returns an |
public default LongStream | Returns: the new streama non-interfering,
stateless
function that generates replacement elements mapper)Returns a |
public DoubleStream | Returns: the new streama non-interfering,
stateless
function to apply to each element mapper)Returns a |
public IntStream | Returns: the new streama non-interfering,
stateless
function to apply to each element mapper)Returns an |
public LongStream | Returns: the new streama non-interfering,
stateless
function to apply to each element mapper)Returns a |
public Optional | Returns: anOptional describing the maximum element of this stream,
or an empty Optional if the stream is emptyReturns the maximum element of this stream according to the provided
|
public Optional | Returns: anOptional describing the minimum element of this stream,
or an empty Optional if the stream is emptyReturns the minimum element of this stream according to the provided
|
public boolean | Returns: true if either no elements of the stream match the
provided predicate or the stream is empty, otherwise false a non-interfering,
stateless
predicate to apply to elements of this stream predicate)Returns whether no elements of this stream match the provided predicate. |
public static < the type of stream elements T> Stream | Returns: a singleton sequential streamthe single element t)Returns a sequential |
public static < the type of stream elements T> Stream | Returns: the new streamthe elements of the new stream values)Returns a sequential ordered stream whose elements are the specified values. |
public static < the type of stream elements T> Stream | Returns: a stream with a single element if the specified element is non-null, otherwise an empty streamthe single element t)Returns a sequential |
public Stream | Returns: the new streama
non-interfering action to perform on the elements as
they are consumed from the stream action)Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. |
public T | Returns: the result of the reductionthe identity value for the accumulating function identity, BinaryOperator<T> accumulator)Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. |
public Optional | Returns: anOptional describing the result of the reductionPerforms a reduction on the
elements of this stream, using an
associative accumulation
function, and returns an |
public < The type of the result U> U | Returns: the result of the reductionthe identity value for the combiner function identity, BiFunction<U, ? super T, U> an associative,
non-interfering,
stateless
function for incorporating an additional element into a result accumulator, BinaryOperator<U> an associative,
non-interfering,
stateless
function for combining two values, which must be
compatible with the accumulator function combiner)Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. |
public Stream | Returns: the new streamthe number of leading elements to skip n)Returns a stream consisting of the remaining elements of this stream
after discarding the first |
public Stream | Returns: the new streamReturns a stream consisting of the elements of this stream, sorted according to natural order. |
public Stream | Returns: the new streamReturns a stream consisting of the elements of this stream, sorted
according to the provided |
public default Stream | Returns: the new streama non-interfering,
stateless
predicate to apply to elements to determine the longest
prefix of elements. predicate)Returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. |
public Object[] | |
public < the component type of the resulting array A> A[] | Returns: an array containing the elements in this streama function which produces a new array of the desired
type and the provided length generator)Returns an array containing the elements of this stream, using the
provided |
public default List | Returns: a List containing the stream elementsAccumulates the elements of this stream into a |