Java Reference
In-Depth Information
5.7.3. Streams from files
Java's NIO API (non-blocking I/O), which is used for I/O operations such as processing a file,
has been updated to take advantage of the Streams API. Many static methods in
java.nio.file.Files return a stream. For example, a useful method is Files.lines, which returns a
stream of lines as strings from a given file. Using what you've learned so far, you could use this
method to find out the number of unique words in a file as follows:
You use Files.lines to return a stream where each element is a line in the given file. You then
split each line into words by calling the split method on line. Notice how you use flatMap to
produce one flattened stream of words instead of multiple streams of words for each line. Finally,
you count each distinct word in the stream by chaining the methods distinct and count.
5.7.4. Streams from functions: creating infinite streams!
The Streams API provides two static methods to generate a stream from a function:
Stream.iterate and Stream.generate. These two operations let you create what we call an infinite
stream : a stream that doesn't have a fixed size like when you create a stream from a fixed
collection. Streams produced by iterate and generate create values on demand given a function
and can therefore calculate values forever! It's generally sensible to use limit(n) on such streams
to avoid printing an infinite number of values.
Iterate
Let's look at a simple example of how to use iterate before we explain it:
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);
 
Search WWH ::




Custom Search