Streams allows us to process data in a declarative way.
Functional Programming is a subset of Declarative programming which treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. It emphasizes on immutability, pure functions, and declarative code. Streams were introduced to process a collection in a functional way.
A Stream is a conduit / channel for data flow. It is not a source of data but only the channel. Streams are generated from a data source and any operations performed of streams does not modify data in the data source. For an analogy take water tank as the data source and the pipe from which data flows as streams.
Java provides the Streams API with a BaseStream
interface. The signature of this interface is —
interface BaseStream<T, S extends BaseStream<T, S>> extends AutoCloseable {...}
T
is the type of elements of the stream and S
is the actual subclass of the BaseStream
interface, This is necessary for fluent interface — method chaining. It is called as Self-referencing generics, it simply means that the actual subclass should be a subclass of BaseStream
.
Read More — https://justgokus.medium.com/what-is-the-fluent-interface-design-pattern-177b9cc93c75
The BaseStream interface has the multiple fundamental methods to perform operations on stream such as iterator();
parallel();
sequential();
close();
etc
Since, the BaseStream
interface extends the AutoCloseable
interface we can use it with the try-with-resource
block for any external data stream such as files. We can also close the stream explicitly using the close()
method. To make the stream parallel we can call the parallel()
method on it and to revert it to sequential stream we can call sequential()
. The iterator()
method returns an Iterator
, based on which we can iterate over the stream.
Generally the Stream
Interface is used which extends the BaseStream
and provides more functionality on top of it such as mapping, filtering, reducing, collecting etc.
Lets say we have a Movie object with 2 fields - name and likes. We have a list of movies and we need to get the count of the movies that have more than 10 likes, Let’s solve the problem using both the approaches: Imperative & Functional.
Using Imperative —