java 8 (Stream API)
Source: Dev.to
Features of Stream API
- Declarative – Write concise and readable code using functional style.
- Lazy Evaluation – Operations are executed only when a terminal operation is needed.
- Parallel Execution – Supports parallel streams to leverage multi‑core processors.
- Reusable Operations – Supports chaining of operations like
map(),filter(),sorted(). - No Storage – Streams don’t store data; they only process it.
How Stream works internally?
- Create a stream – From collections, arrays, or static methods.
- Apply intermediate operations – Transform data (e.g.,
filter(),map(),sorted()). - Apply terminal operation – Produce a result (e.g.,
forEach(),collect(),reduce()).
Creation of streams
- From a Collection –
list.stream()orset.stream(). - From an Array –
Arrays.stream(array). - Using
Stream.of()– Create a stream from a fixed set of values. - Infinite Stream – Generate an unbounded sequence with
Stream.iterate()orStream.generate().


Intermediate operations
Intermediate operations transform a stream into another stream. Common ones include:
filter()– Filters elements based on a condition.map()– Transforms each element to another value.sorted()– Sorts the elements.distinct()– Removes duplicates.skip()– Skips the first n elements.


Types of streams
Sequential Stream
Processes elements one by one in a single thread. Created by default when you call stream().


Parallel Streams
Can perform operations concurrently on multiple threads, taking advantage of multi‑core CPUs.
Infinite Streams
Generate unbounded sequences. Use limit() to avoid infinite execution.

