Core Java for the Impatient by Cay S. Horstmann
Author:Cay S. Horstmann [Horstmann, Cay S.]
Language: eng
Format: epub, pdf
Publisher: Pearson Education
Published: 2015-01-29T22:00:00+00:00
8.1 From Iterating to Stream Operations
When you process a collection, you usually iterate over its elements and do some work with each of them. For example, suppose we want to count all long words in a book. First, let’s put them into a list:
Click here to view code image
String contents = new String(Files.readAllBytes(
Paths.get("alice.txt")), StandardCharsets.UTF_8); // Read file into string
List<String> words = Arrays.asList(contents.split("\\PL+"));
// Split into words; nonletters are delimiters
Now we are ready to iterate:
Click here to view code image
int count = 0;
for (String w : words) {
if (w.length() > 12) count++;
}
With streams, the same operation looks like this:
Click here to view code image
long count = words.stream()
.filter(w -> w.length() > 12)
.count();
Now you don’t have to scan the loop for evidence of filtering and counting. The method names tell you right away what the code intends to do. Moreover, where the loop prescribes the order of operations in complete detail, a stream is able to schedule the operations any way it wants, as long as the result is correct.
Simply changing stream into parallelStream allows the stream library to do the filtering and counting in parallel.
Click here to view code image
long count = words.parallelStream()
.filter(w -> w.length() > 12)
.count();
Streams follow the “what, not how” principle. In our stream example, we describe what needs to be done: get the long words and count them. We don’t specify in which order, or in which thread, this should happen. In contrast, the loop at the beginning of this section specifies exactly how the computation should work, and thereby forgoes any chances of optimization.
A stream seems superficially similar to a collection, allowing you to transform and retrieve data. But there are significant differences:
1. A stream does not store its elements. They may be stored in an underlying collection or generated on demand.
2. Stream operations don’t mutate their source. For example, the filter method does not remove elements from a new stream, but it yields a new stream in which they are not present.
3. Stream operations are lazy when possible. This means they are not executed until their result is needed. For example, if you only ask for the first five long words instead of all, the filter method will stop filtering after the fifth match. As a consequence, you can even have infinite streams!
Let us have another look at the example. The stream and parallelStream methods yield a stream for the words list. The filter method returns another stream that contains only the words of length greater than twelve. The count method reduces that stream to a result.
This workflow is typical when you work with streams. You set up a pipeline of operations in three stages:
1. Create a stream.
2. Specify intermediate operations for transforming the initial stream into others, possibly in multiple steps.
3. Apply a terminal operation to produce a result. This operation forces the execution of the lazy operations that precede it. Afterwards, the stream can no longer be used.
In our example, the stream was created with the stream or parallelStream method. The filter method transformed it, and count was the terminal operation.
Download
Core Java for the Impatient by Cay S. Horstmann.pdf
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Ajax | Assembly Language Programming |
Borland Delphi | C & C++ |
C# | CSS |
Compiler Design | Compilers |
DHTML | Debugging |
Delphi | Fortran |
Java | Lisp |
Perl | Prolog |
Python | RPG |
Ruby | Swift |
Visual Basic | XHTML |
XML | XSL |
Deep Learning with Python by François Chollet(12587)
Hello! Python by Anthony Briggs(9924)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9800)
The Mikado Method by Ola Ellnestam Daniel Brolund(9784)
Dependency Injection in .NET by Mark Seemann(9347)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(8309)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7770)
Grails in Action by Glen Smith Peter Ledbrook(7704)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7566)
Becoming a Dynamics 365 Finance and Supply Chain Solution Architect by Brent Dawson(7139)
Microservices with Go by Alexander Shuiskov(6901)
Practical Design Patterns for Java Developers by Miroslav Wengner(6819)
Test Automation Engineering Handbook by Manikandan Sambamurthy(6759)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(6422)
Angular Projects - Third Edition by Aristeidis Bampakos(6178)
The Art of Crafting User Stories by The Art of Crafting User Stories(5699)
NetSuite for Consultants - Second Edition by Peter Ries(5630)
Demystifying Cryptography with OpenSSL 3.0 by Alexei Khlebnikov(5443)
Kotlin in Action by Dmitry Jemerov(5072)
