GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.oracle.com — java.util.stream (Java SE 16 & JDK 16) Module java.base
Package java.util.streampackage java.util.stream
Classes to support functional-style operations on streams of elements, such
as map-reduce transformations on collections. For example:
Here we use The key abstraction introduced in this package is stream. The
classes
Additional stream sources can be provided by third-party libraries using these techniques. Stream operations and pipelinesStream operations are divided into intermediate and
terminal operations, and are combined to form stream
pipelines. A stream pipeline consists of a source (such as a
Intermediate operations return a new stream. They are always
lazy; executing an intermediate operation such as
Terminal operations, such as Processing streams lazily allows for significant efficiencies; in a pipeline such as the filter-map-sum example above, filtering, mapping, and summing can be fused into a single pass on the data, with minimal intermediate state. Laziness also allows avoiding examining all the data when it is not necessary; for operations such as "find the first string longer than 1000 characters", it is only necessary to examine just enough strings to find one that has the desired characteristics without examining all of the strings available from the source. (This behavior becomes even more important when the input stream is infinite and not merely large.) Intermediate operations are further divided into stateless
and stateful operations. Stateless operations, such as Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream. As a result, under parallel computation, some pipelines containing stateful intermediate operations may require multiple passes on the data or may need to buffer significant data. Pipelines containing exclusively stateless intermediate operations can be processed in a single pass, whether sequential or parallel, with minimal data buffering. Further, some operations are deemed short-circuiting operations. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time. Having a short-circuiting operation in the pipeline is a necessary, but not sufficient, condition for the processing of an infinite stream to terminate normally in finite time. ParallelismProcessing elements with an explicit
The only difference between the serial and parallel versions of this
example is the creation of the initial stream, using " Except for operations identified as explicitly nondeterministic, such
as Most stream operations accept parameters that describe user-specified
behavior, which are often lambda expressions. To preserve correct behavior,
these behavioral parameters must be non-interfering, and in
most cases must be stateless. Such parameters are always instances
of a functional interface such
as Non-interferenceStreams enable you to execute possibly-parallel aggregate operations over a variety of data sources, including even non-thread-safe collections such asArrayList. This is possible only if we can prevent
interference with the data source during the execution of a stream
pipeline. Except for the escape-hatch operations iterator() and
spliterator(), execution begins when the terminal operation is
invoked, and ends when the terminal operation completes. For most data
sources, preventing interference means ensuring that the data source is
not modified at all during the execution of the stream pipeline.
The notable exception to this are streams whose sources are concurrent
collections, which are specifically designed to handle concurrent modification.
Concurrent stream sources are those whose Spliterator reports the
CONCURRENT characteristic.
Accordingly, behavioral parameters in stream pipelines whose source might not be concurrent should never modify the stream's data source. A behavioral parameter is said to interfere with a non-concurrent data source if it modifies, or causes to be modified, the stream's data source. The need for non-interference applies to all pipelines, not just parallel ones. Unless the stream source is concurrent, modifying a stream's data source during execution of a stream pipeline can cause exceptions, incorrect answers, or nonconformant behavior. For well-behaved stream sources, the source can be modified before the terminal operation commences and those modifications will be reflected in the covered elements. For example, consider the following code:
First a list is created consisting of two strings: "one" and "two". Then a
stream is created from that list. Next the list is modified by adding a third
string: "three". Finally the elements of the stream are collected and joined
together. Since the list was modified before the terminal collect
operation commenced the result will be a string of "one two three". All the
streams returned from JDK collections, and most other JDK classes,
are well-behaved in this manner; for streams generated by other libraries, see
Low-level stream
construction for requirements for building well-behaved streams.
Stateless behaviorsStream pipeline results may be nondeterministic or incorrect if the behavioral parameters to the stream operations are stateful. A stateful lambda (or other object implementing the appropriate functional interface) is one whose result depends on any state which might change during the execution of the stream pipeline. An example of a stateful lambda is the parameter tomap() in:
Here, if the mapping operation is performed in parallel, the results for the
same input could vary from run to run, due to thread scheduling differences,
whereas, with a stateless lambda expression the results would always be the
same.
Note also that attempting to access mutable state from behavioral parameters presents you with a bad choice with respect to safety and performance; if you do not synchronize access to that state, you have a data race and therefore your code is broken, but if you do synchronize access to that state, you risk having contention undermine the parallelism you are seeking to benefit from. The best approach is to avoid stateful behavioral parameters to stream operations entirely; there is usually a way to restructure the stream pipeline to avoid statefulness. Side-effectsSide-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.If the behavioral parameters do have side-effects, unless explicitly stated, there are no guarantees as to:
The ordering of side-effects may be surprising. Even when a pipeline is
constrained to produce a result that is consistent with the
encounter order of the stream source (for example,
The eliding of side-effects may also be surprising. With the exception of
terminal operations Many computations where one might be tempted to use side-effects can be more
safely and efficiently expressed without side-effects, such as using
reduction instead of mutable
accumulators. However, side-effects such as using As an example of how to transform a stream pipeline that inappropriately uses side-effects to one that does not, the following code searches a stream of strings for those matching a given regular expression, and puts the matches in a list.
This code unnecessarily uses side-effects. If executed in parallel, the
non-thread-safety of ArrayList would cause incorrect results, and
adding needed synchronization would cause contention, undermining the
benefit of parallelism. Furthermore, using side-effects here is completely
unnecessary; the forEach() can simply be replaced with a reduction
operation that is safer, more efficient, and more amenable to
parallelization:
OrderingStreams may or may not have a defined encounter order. Whether
or not a stream has an encounter order depends on the source and the
intermediate operations. Certain stream sources (such as If a stream is ordered, most operations are constrained to operate on the
elements in their encounter order; if the source of a stream is a For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results. For parallel streams, relaxing the ordering constraint can sometimes enable
more efficient execution. Certain aggregate operations,
such as filtering duplicates ( Reduction operationsA reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, calledreduce()
and collect(),
as well as multiple specialized reduction forms such as
sum(), max(),
or count().
Of course, such operations can be readily implemented as simple sequential loops, as in:
However, there are good reasons to prefer a reduce operation
over a mutative accumulation such as the above. Not only is a reduction
"more abstract" -- it operates on the stream as a whole rather than individual
elements -- but a properly constructed reduce operation is inherently
parallelizable, so long as the function(s) used to process the elements
are associative and
stateless.
For example, given a stream of numbers for which we want to find the sum, we
can write:
or:
These reduction operations can run safely in parallel with almost no modification:
Reduction parallellizes well because the implementation
can operate on subsets of the data in parallel, and then combine the
intermediate results to get the final correct answer. (Even if the language
had a "parallel for-each" construct, the mutative accumulation approach would
still required the developer to provide
thread-safe updates to the shared accumulating variable The "widgets" examples shown earlier shows how reduction combines with
other operations to replace for-loops with bulk operations. If
In its more general form, a
Here, the identity element is both an initial seed value for the reduction
and a default result if there are no input elements. The accumulator
function takes a partial result and the next element, and produces a new
partial result. The combiner function combines two partial results
to produce a new partial result. (The combiner is necessary in parallel
reductions, where the input is partitioned, a partial accumulation computed
for each partition, and then the partial results are combined to produce a
final result.)
More formally, the The three-argument form is a generalization of the two-argument form, incorporating a mapping step into the accumulation step. We could re-cast the simple sum-of-weights example using the more general form as follows:
though the explicit map-reduce form is more readable and therefore should
usually be preferred. The generalized form is provided for cases where
significant work can be optimized away by combining mapping and reducing
into a single function.
Mutable reductionA mutable reduction operation accumulates input elements into a mutable result container, such as aCollection or StringBuilder,
as it processes the elements in the stream.
If we wanted to take a stream of strings and concatenate them into a single long string, we could achieve this with ordinary reduction:
We would get the desired result, and it would even work in parallel. However,
we might not be happy about the performance! Such an implementation would do
a great deal of string copying, and the run time would be O(n^2) in
the number of characters. A more performant approach would be to accumulate
the results into a The mutable reduction operation is called
As with
Or we could use a parallelizable collect form:
or, pulling the mapping operation out of the accumulator function, we could
express it more succinctly as:
Here, our supplier is just the ArrayList constructor, the accumulator adds the stringified element to an
ArrayList, and the combiner simply uses addAll
to copy the strings from one container into the other.
The three aspects of
Packaging mutable reductions into a Collector has another advantage:
composability. The class
(The ? for the second type parameter merely indicates that we don't
care about the intermediate representation used by this collector.)
If we wanted to create a collector to tabulate the sum of salaries by
department, we could reuse summingSalaries using
groupingBy:
As with the regular reduction operation, Further, however the computation is split, it must produce an equivalent
result. For any input elements
Here, equivalence generally means according to Reduction, concurrency, and orderingWith some complex reduction operations, for example acollect() that
produces a Map, such as:
it may actually be counterproductive to perform the operation in parallel.
This is because the combining step (merging one Map into another by
key) can be expensive for some Map implementations.
Suppose, however, that the result container used in this reduction
was a concurrently modifiable collection -- such as a
A
BaseStream.unordered() method. For example:
(where Collectors.groupingByConcurrent(java.util.function.Function<? super T, ? extends K>) is the
concurrent equivalent of groupingBy).
Note that if it is important that the elements for a given key appear in the order they appear in the source, then we cannot use a concurrent reduction, as ordering is one of the casualties of concurrent insertion. We would then be constrained to implement either a sequential reduction or a merge-based parallel reduction. AssociativityAn operator or functionop is associative if the following
holds:
The importance of this to parallel evaluation can be seen if we expand this
to four terms:
So we can evaluate (a op b) in parallel with (c op d), and
then invoke op on the results.
Examples of associative operations include numeric addition, min, and max, and string concatenation. Low-level stream constructionSo far, all the stream examples have used methods likeCollection.stream() or Arrays.stream(Object[])
to obtain a stream. How are those stream-bearing methods implemented?
The class There are a number of implementation choices in implementing a
spliterator, nearly all of which are tradeoffs between simplicity of
implementation and runtime performance of streams using that spliterator.
The simplest, but least performant, way to create a spliterator is to
create one from an iterator using
A higher-quality spliterator will provide balanced and known-size
splits, accurate sizing information, and a number of other
Spliterators for mutable data sources have an additional challenge;
timing of binding to the data, since the data could change between the time
the spliterator is created and the time the stream pipeline is executed.
Ideally, a spliterator for a stream would report a characteristic of
These requirements significantly reduce the scope of potential interference between mutations of the stream source and execution of stream pipelines. Streams based on spliterators with the desired characteristics, or those using the Supplier-based factory forms, are immune to modifications of the data source prior to commencement of the terminal operation (provided the behavioral parameters to the stream operations meet the required criteria for non-interference and statelessness). See Non-Interference for more details.
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |