Understanding the Hierarchy of Java Stream
When we write code for java streams, we take a source, apply intermediate operations to it, and add a terminal operation.
These intermediate operations can be filtering out even elements, sorting all the elements or having distinct elements.
In the terminal operations, you can have operations like the sum/average of all the elements or simply adding the items in a collection.
Using stream makes the code clean, readable and also efficient due to lazy evaluation. It creates a pipeline of functions where all the elements go through these functions in one go. This pipeline does not have any storage, it's only an abstraction over the given source.
Hierarchy of streams:
There are mainly 5 interfaces of streams:
- BaseStream: It provides methods like parallel(), sequential() and unordered().
- IntStream: It is used for streams of primitive int.
- LongStream: It is used for streams of primitive long.
- DoubleStream: It is used for streams of primitive double.
- Stream<T>: It is used for non-primitives.
Some common methods of all these interfaces are:
filter(): It is an intermediate operation, that takes a predicate as an argument and filters out the element according to the given predicate.
sorted(): It is an intermediate operation, that takes a stream and returns the sorted version of that stream.
forEach(): It is a terminal method and takes an action as an argument, and performs the given action on each element of the stream.
findFirst(): It is a terminal operation that is used to find the first element of the stream.
collect(): It is a terminal operation that is used to convert a stream into a collection. (for example, if you want to get the data in a collection like an ArrayList, you can use the collect() method)
The below methods are available only in IntStream, LongStream and DoubleStream:
sum(): It is used to get the sum of all the elements in the stream.
average(): It is used to get the average of all the elements in the stream.
boxed(): It is used to create a stream which is a non-primitive stream. (for example Long or Integer)