Java Reference
In-Depth Information
for loop is a reasonable solution for performing iteration, it is both a non-intuitive and
verbose strategy. In Java 8, the boilerplate of iterating over Collections has been
removed, along with the requirement to spell out how the iteration is to be completed.
The compiler already knows how to iterate over a Collection , so why tell the com-
piler exactly how to do it? Why not simply tell the compiler: “I would like to iterate
over this Collection , and perform this task on each element”? The concept of
streams enables this hands-off approach to iteration.
Let the compiler take care of the non-intuitive looping, and simply hand the task off
to the compiler and tell it what action to perform on each element. This concept is
known as internal iteration. With internal iteration, your application determines what
needs to be iterated, and the JDK decides how to perform the iteration. Internal itera-
tion not only alleviates the requirement to program the looping logic, but it also has
other advantages. One such advantage is that internal iteration is not limited to sequen-
tial iteration over elements. Therefore, the JDK decides how to iterate, choosing the
best algorithm for the task at hand. Internal iteration also can more easily take advant-
age of parallel computing. This concept involves subdividing tasks into smaller prob-
lems, solving each in a simultaneous manner, and then combining the results.
A stream is a sequence of object references that can be generated on all Collec-
tion types. The Stream API makes it possible to perform a sequence of aggregate op-
erations upon those object references and either return a result or apply the changes to
the objects inline. This is also known as a pipeline . The pseudocode for generation and
use of a stream is as follows:
Collection -> (Stream) -> (Zero or More Intermediate
Operations) -> (Terminal Operation)
Let's put this pseudocode into a real example. In the solution, a list of Stock ob-
jects is used for demonstrating stream iteration. Let's suppose you want to print out
each stock that contains a number of shares that is over a designated threshold (100
shares in this example). You can use the following code to perform this task:
myStocks.stream()
.filter(s -> s.getShares() > 100.0)
.forEach(s->System.out.println(s.getName()));
In the previous example, an intermediate operation known as a filter() is used
to apply a limitation on the elements, thereby filtering out all of the elements that do
not match the supplied predicate. The predicate is written in the form of a lambda ex-
Search WWH ::




Custom Search