Java Reference
In-Depth Information
5.7. Building streams
Hopefully by now you're convinced that streams are very powerful and useful to express data
processing queries. So far, you were able to get a stream from a collection using the stream
method. In addition, we showed you how to create numerical streams from a range of numbers.
But you can create streams in many more ways! This section shows how you can create a stream
from a sequence of values, from an array, from a file, and even from a generative function to
create infinite streams!
5.7.1. Streams from values
You can create a stream with explicit values by using the static method Stream.of, which can
take any number of parameters. For example, in the following code you create a stream of
strings directly using Stream.of. You then convert the strings to uppercase before printing them
one by one:
Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action") ;
stream.map(String::toUpperCase).forEach(System.out::println);
You can get an empty stream using the empty method as follows:
Stream<String> emptyStream = Stream.empty() ;
5.7.2. Streams from arrays
You can create a stream from an array using the static method Arrays.stream, which takes an
array as parameter. For example, you can convert an array of primitive ints into an IntStream as
follows:
 
Search WWH ::




Custom Search