Skip to main content
Advertisement

Stream API Overview

Introduced in Java 8, the Stream API allows developers to process sequences of elements (such as arrays, Lists, Sets, and Maps) in a declarative manner by applying functional interfaces (lambda expressions).

Streams dramatically reduce the complexity and boilerplate code associated with traditional for loops or Iterators, enabling data manipulation much like database queries.

1. Characteristics of Streams

  1. Read-only (No Modification): Streams process and transform elements from a source but never modify the original data source.
  2. One-time Use (Consumable): A stream can be traversed only once. After it has been consumed by a terminal operation, it is closed and cannot be reused. A new stream must be created if needed.
  3. Internal Iteration: Unlike external iteration where the developer explicitly writes loops (for, while), streams handle the iteration internally. This leads to much cleaner and more concise code.

2. The Stream Pipeline

Stream operations are structured like a pipeline. They can be broadly divided into three stages: Creation, ** Intermediate Operations**, and ** Terminal Operations**.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

long count = names.stream() // 1. Creation
.filter(n -> n.length() > 3) // 2. Intermediate Operation (Filtering)
.count(); // 3. Terminal Operation (Counting)

Lazy Evaluation

One of the most important features of a stream is that no intermediate operations are actually executed until a terminal operation is invoked. This is known as "Lazy Evaluation". Data only begins to flow through the pipeline when the final result is requested, which prevents unnecessary processing and optimizes performance.

3. Creating a Stream

Here are the standard ways to create streams from collections and arrays:

// 1. From a Collection (List, Set, etc.)
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> streamFromList = list.stream();

// 2. From an Array
String[] arr = {"A", "B", "C"};
Stream<String> streamFromArray = Arrays.stream(arr);

// 3. For a specific range of numbers (IntStream)
IntStream intStream = IntStream.rangeClosed(1, 10); // 1 to 10 inclusive

In the next section, we will explore the core of stream processing: Intermediate Operations.

Advertisement