![]() |
VOOZH | about |
A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function's output in a stream depends only on its input arguments. A stream holds no non-transient stage. Every stream works essentially the same which is:
By default, each aggregate operation in a stream runs its function sequentially, i.e., one after another in the caller's thread of control. Streams can be created from Collections, Lists, Sets, ints, longs, doubles, arrays, lines of a file.
Stream operations are either intermediate or terminal. Intermediate operations such as filter, map, or sort return a stream, so we can chain multiple intermediate operations. Terminal operations such as forEach, collect, or reduce are either void or return a non-stream result. Streams bring functional programming in Java and are supported starting in Java 8. The Java 8 stream is an implementation of the PQSA1 Pipes and Filter pattern.
Example:
Integer Stream :
123456789
Integer Stream with skip :
6
7
8
9
Integer Stream with sum :
10
Stream.of, sorted and findFirst :
Java
Stream from Array, sort, filter and print :
Scikit
Average of squares of an int array :
44.0
Stream from List, filter and print :
ai
Reduction - sum :
Total = 13.600000000000001
Reduction - summary statistics :
IntSummaryStatistics{count=7, sum=203, min=2, average=29.000000, max=88}
Now, discussing loops in order to figure out in order to land onto conclusive differences. Looping is a feature in Java that facilitates the execution of a set of instructions until the controlling Boolean expression evaluates to false. Different types of loops are provided to fit any programming need. Each loop has its own purpose and a suitable use case to serve.
Example:
[2000, 1500, 2500]
By far we have understood both of the concepts and come across to know they don't go hand in hand, one has advantage over other as per the usage where it is to be used. Hence, wrapping off the article by illustrating their advantages which are as follows:
Advantages of Streams
Advantages of Loops
Conclusion:
If you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead.