top of page

Streams In Java

Updated: Dec 20, 2022



Java recently launched version 17 but still, Java 8 is a Pro player. The main reason is features that come under Java 8. One of them is a stream.


Java provides one separate package with the name of java.util.stream. As you can see it is under util so it will contain some utility methods, classes, and interfaces.


Let's start with interfaces first. Stream packages contain interfaces like BaseStream, IntStream, LongStream, DoubleStream, and Stream<T>.


The most popular interfaces among them are Strem<T> which is containing varieties of methods to manipulate the data.


Before starting the concept first discuss the stream.


Why Stream?

Obviously, if Java is providing something that means important! Basically, Java already provided a powerful API for managing the data structure using Collection but, modification in collections was a bit tricky and difficult specifically with lists and maps. Java knows that problem but without functional programming, it was not possible to manage all this stuff so they introduced lambda in Java 8 and that was the point where everything changed. One of the hardcore Object-oriented lover changed their mind because of the sustainability problem in the market. Here we learned why stream... Let's move on and learn what is stream.


What is Stream?

Stream is not storage like we have List, ArrayList, and other data structures available in Collection API. Stream doesn't even change anything in the source. Every time it will generate a new stream whenever you will try to use any operation of stream on your available data. The worst part of the stream is you cannot iterate again on your stream you need to create new stream when you want to iterate.


Stream is Lazy in nature!

For understanding the concept of laziness, we have to understand the eager loading and lazy loading. In case of eager loading, you will have your whole data in a single click like the center fruit advertisement guy who provides a whole menu card but in case of lazy loading, one by data will process with permission like "man hai" uncle.


While you are dealing with bigger data, we should not use the eager loading. Because in eager loading, we are not sure how the processed data will be used. It will always process the entire amount of data at the cost of performance. In lazy processing, the operations are performed after the action. It is processing the data only on demand.


It is an important characteristic of streams because the operation on the source data is only performed when the terminal operation is initiated. It doesn’t consume the source elements as in eager loading, the source elements are consumed only on demand.

As you have seen in Stream operations:

1. The intermediate stream doesn’t produce the result. They create a new Stream

only.

2. The terminal operation produces the result.




We, Will, Discuss the Stream interface in detail in the next Post.



Σχόλια


bottom of page