Java streams are very powerful to process queries against streams of elements such as sum values in list or filtering elements in a collection. This example will show how to create a stream from values, from an array, file or even create an infinite stream from a function.
Stream from values
By using the static method Stream.of, you can create a sequential ordered stream whose elements are values specified. In example below, we create a stream of strings, trim each element and then join each of them seperated by a comma while returning a string.
Empty stream
Stream from array
You can create a stream from an array by calling the static method Arrays.stream which accepts an array as a parameter. In the example below, we convert an array of ints into an Instream then calling the sum method.
Stream from file
Working with files in Java was completely revamped in Java 7 and enhanced in Java 8 to take advantage of the Stream API. The example below shows how to count the number of distinct words in a file by using java.nio.file.Files which contains a useful method Files.line which returns a stream of strings from a specifed file. Breaking it down further, we read the file line by line splitting the words on a space and a period then taking distinct of all of the elements of the single stream produced by the flatMap.
Stream from function
In the example below, we use Stream.iterate which allows us to call infinite streams, a stream with out a fixed size. In stream filter and slice example, we showed how to limit a stream or truncate it by a specified value which we use below so we don't calculate values forever.
Output
Stream from generate
Similar to the Stream.iterate method above, the Stream.generate allows you to produce an infinite stream of values on demand. The code below will generate a stream of 10 random double numbers from 0 to 1 and we apply the limit otherwise the stream would be unbounded.
Output