Let's Go to the Java Stream
Ahhh — refreshing stream, rushing over the rocks in the forest. Ok, not that type of stream. Java API stream allows the application of multiple operations one after another(stream them, kind of like some beads on a string) to the groups of objects (Collections, Arrays, I/O resources).
First, we need to obtain a stream. It is important to notice that stream is not a data structure, it does not change the initial data. Obtaining streams could be done in a number of ways. Collection interface has method for this:
List<String> lettersList = Arrays.asList("a", "b", "c", "d", "ef");
lettersList.stream();
Operations that could be performed on the stream are divided into intermediate and terminal and are part of the stream pipeline. A stream pipeline consists of a source, zero or more intermediate operations, and a terminal operation.
Let's look at the example of stream pipeline where is intermediate operation and the is terminal:
long numberOfLetters = lettersList.stream()
.filter(letter -> letter.length() > 0)
.count();
Intermediate operations are lazy, which means they are not starting their execution until the terminal operation is executed. Such laziness leads to noticeable efficiency.
We can perform multiple operations in a single pass of data, and sometimes we don’t have to examine all the data, we just need to find the first case that satisfies our condition.
After terminal operation is executed the stream is considered consumed and can not be used. If there is a need to transverse the data again, the new stream needs to be obtained.
is just a wrapper for the data that allows bulk processing to be fast and convenient.
Happy coding my friends!
Code could be found here: