java Streams Java 8

In my previous articles related to features in java 8, I explained lambda expressions and functional interfaces. In this article I will discuss about another great feature introduced in java 8, Streams.
Streams heavily use functional interfaces and lamdas so i will recommend to go through these articles if you are not familiar with them.

What is a stream:-  In very basic terms stream means  never ending incoming data. In natural world , if you think about a stream the first thing which comes to mind is stream of water, the stream originates from some source(river, sea, glaciers etc.) and the content of the stream(water) is the same as of the source. Similarly , in java, the source of a stream is a Collection. The datatype of data in stream is the same as of the data in source.


Why do we need stream:-  Streams allow functional programming easily, hence making the code short as well as readable. Lets understand this with an example . The program below adds all numbers in an array which are greater than 5 and then returns the value.




To this simple operation we need to write so many lines of code. By using streams and functional programming we can do it in one line which makes our code much more readable.



To understand this code , lets understand some basic concepts about streams. Essentially streams allow you to perform chain of operations on the initial data which is referred to as pipelining of operations and at the termination, you can collect the result . So stream processing is divided in two parts:-
1. Pipelining of processes through which each input data passes.
2. Termination stage or data collection stage.

In this example the source of the stream is list. Then we perform two processes(pipeline) ,filter and mapToInt. Finally we call the sum function on the IntStream  returned by the mapToInt function.

In future articles, I will explain in details about different functions used in java streams. I hope this article was helpful.


Comments

Popular Posts