Introduction
In this short blog article, I want to show the various sources like collections, arrays, files, and more, from which streams can be created.
One of the first steps in using streams is to create a stream source, which is the starting point of the data stream.
1. Collections
One of the most used ways to create a stream is from a collection. You can directly use the stream() operation on the collection.
2. Arrays
For Arrays you can use the static Stream.of() method to create a stream from an array.
3. I/O
You can create a stream from an I/O source, such as a file or network socket, using the Files.lines()
or BufferedReader.lines()
methods. For example, to read the lines of a file into a stream of strings,
4. Generate and Iterate
Java also provides two static methods, Stream.generate() and Stream.iterate(), that allows you to create an infinite stream of elements.
Check out the Collectors article for more information how to use it efficiently.