Search⌘ K
AI Features

Stream API Basics

Explore the basics of the Java Stream API to transform and process data collections declaratively. Understand how to build pipelines using intermediate operations like filter and map, and execute results with terminal operations such as collect and reduce. Learn lazy evaluation and short-circuiting to write efficient, modern Java code focused on what to do rather than how to iterate.

Until now, we have mostly applied these tools to single tasks or simple behaviors. However, the real power of functional programming in Java emerges when we apply these concepts to data processing.

Traditionally, processing a list of items required writing verbose for loops, managing temporary variables, and mixing what we want to do with how to do it. This approach is often error-prone and hard to read. In this lesson, we will introduce the Stream API, a powerful toolkit that allows us to process data using clean, readable pipelines that separate logic from iteration.

The stream pipeline model

A Stream in Java is a sequence of elements supporting sequential and parallel aggregate operations. It is important to understand that a stream is not a data structure. Unlike a List or Array, a stream does not store data; instead, it conveys elements from a source through a pipeline of computational steps.

A stream pipeline consists of three distinct stages:

  1. Source: Where the data originates (e.g., a Collection, an Array, or an I/O channel).

  2. Intermediate operations: Transformative steps (e.g., filter, map) that return a new stream. These are lazy, meaning they do not execute immediately.

  3. Terminal operation: The final step (e.g., collect, reduce) that produces a result ...