Java Reference
In-Depth Information
cat file1 file2 | tr "[A-Z]" "[a-z]" | sort | tail -3
which (supposing file1 and file2 contain a single word per line) prints the three words from the
files that appear latest in dictionary order, after first translating them to lowercase. We say that
sort takes a stream of lines [ 3 ] as input and produces another stream of lines as output (the latter
being sorted), as illustrated in figure 1.2 . Note that in Unix the commands (cat, tr, sort, and tail)
are executed concurrently, so that sort can be processing the first few lines before cat or tr has
finished. A more mechanical analogy is a car-manufacturing assembly line where a stream of
cars is queued between processing stations that each take a car, modify it, and pass it on to the
next station for further processing; processing at separate stations is typically concurrent even
though the assembly line is physically a sequence.
3 Purists will say a “stream of characters,” but it's conceptually simpler to think that sort
reorders lines .
Figure 1.2. Unix commands operating on streams
Java 8 adds a Streams API (note the uppercase S ) in java.util.stream based on this idea;
Stream<T> is a sequence of items of type T. You can think of it as a fancy iterator for now. The
Streams API has many methods that can be chained to form a complex pipeline just like Unix
commands were chained in the previous example.
The key motivation for this is that you can now program in Java 8 at a higher level of abstraction,
structuring your thoughts of turning a stream of this into a stream of that (similarly to how you
think when writing database queries) rather than one item at a time. Another advantage is that
Java 8 can transparently run your pipeline of Stream operations on several CPU cores on
disjoint parts of the input—this is parallelism almost for free instead of hard work using
Threads. We cover the Java 8 Streams API in detail in chapters 4 - 7 .
1.1.3. Passing code to methods with behavior parameterization
The second programming concept added to Java 8 is the ability to pass a piece of code to an API.
This sounds awfully abstract. In the Unix example, you might want to tell the sort command to
 
Search WWH ::




Custom Search