Java Reference
In-Depth Information
pression; it performs the test on each element and returns a Boolean result. The ter-
minal operation in the example uses forEach() to print each of the matching ele-
ments. A terminal operation is the last operation in a pipeline, and it produces a non-
stream result such as a primitive, collection, or no value at all. In the example case, no
result is returned.
To generate a stream on a Collection type, call the stream() method, which
will return a Stream type. In most cases, the Stream type is not the desired result, so
the Stream API makes it possible to invoke zero or more intermediate operations upon
a stream, forming a pipeline of operations. For example, in the solution the list of
Stock objects is sorted by the number of shares using the following code. Note that
Comparator byShares is applied to each object in the stream and a
Stream<Stock> is returned as a result:
Stream<Stock> sortedByShares = myStocks.stream()
.sorted(byShares);
In the previous example, a single intermediate operation, sorted() , is performed
on the stream. As mentioned previously, there could be more than one intermediate op-
eration chained to this pipeline, thereby performing the next operation upon those ob-
jects that meet the criteria of the previous operation. Each of the intermediate opera-
tions returns a Stream . Each pipeline can contain a terminal operation, thereby apply-
ing the terminal operation to each of the resulting stream objects. As mentioned previ-
ously, a terminal operation may or may not return a result. In the previous example, no
terminal operation is applied.
Note The online documentation for Stream ( http://download.java.net/
jdk8/docs/api/java/util/stream/Stream.html ) lists all of the interme-
diate and terminal operations available upon a stream.
Streams are a revolutionary change for the Java programming language. They
change the way in which a developer thinks about a program, making the developer
more productive and the code more efficient. While legacy iteration techniques such as
the for loop are still considered valid procedures, streams are the preferred technique
for iteration when you're using Java 8 or beyond.
Search WWH ::




Custom Search