What is a Stream?

A Stream in Java is a new abstraction introduced in Java 8. It represents a sequence of elements (like a collection) that can be processed in a functional way.

But unlike collections:

  • It doesn’t store data.
  • It operates on data from a source, such as a collection, an array, or I/O channels.
  • It is immutable—you can’t change the original data source.
  • It processes elements using a pipeline of operations.

Why Use Streams?

  • To write cleaner and more readable code.
  • To work with collections in a more expressive way.
  • To avoid writing for-loops and temporary variables.
  • To take advantage of multicore processors using parallel streams.

Stream Operations

There are two main operations on streams

Intermediate Operation

Intermediate operations are used to manipulate or filter data. They always return another Stream and are lazy—they don’t do anything until a terminal operation is called.

Example: map(), filter(), flatMap(), sorted() etc.,

Terminal Operation

Terminal operations trigger the execution of the stream pipeline and produce a result. After a terminal operation, the stream is considered consumed and can’t be reused.

Example: collect(), forEach(), count(), min(), max()

Java Streams are powerful once you understand how to build a pipeline with:

  • A source
  • One or more intermediate operations
  • A terminal operation to produce a result

Each operation is designed to separate logic into manageable steps, allowing you to write code that’s cleaner, more expressive, and often more efficient.

Leave a Comment