Back to course

Deep Dive into the Java Streams API (Filter, Map, Reduce)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 49: Deep Dive into the Java Streams API

The Streams API (Java 8+) is one of the most powerful features for processing sequences of data (collections or arrays) in a functional and declarative style.

1. What is a Stream?

A stream is a sequence of elements that supports sequential and parallel aggregate operations. Crucially, a stream:

  • Is not a data structure: It doesn't store data; it pipelines data from a source (like a List).
  • Is functional: Operations don't modify the source data.
  • Is lazy: Operations are only executed when a terminal operation is called.

2. Stream Pipeline Structure

A stream pipeline consists of three parts:

  1. Source: A collection, array, or I/O resource (list.stream()).
  2. Intermediate Operations: Transform the stream and return a new stream (e.g., filter, map, sorted). These are lazy.
  3. Terminal Operation: Produces a result or side effect (e.g., forEach, collect, reduce, count). This triggers the execution.

3. Core Intermediate Operations

  • filter(): Selects elements matching a given condition (Predicate).
  • map(): Transforms each element into a new value (Function).
  • sorted(): Sorts the elements.

java List words = List.of("apple", "banana", "cat", "dog");

List result = words.stream() // 1. Source .filter(w -> w.length() > 3) // 2. Intermediate (Keeps 'apple', 'banana') .map(String::toUpperCase) // 2. Intermediate (APPLE, BANANA) .collect(Collectors.toList()); // 3. Terminal (Puts results into a new List)

System.out.println(result); // Output: [APPLE, BANANA]

4. The reduce() Operation

reduce() combines all elements in the stream to produce a single result (e.g., sum, product, concatenation).

java List nums = List.of(1, 2, 3, 4); // Sum = 1 + 2 + 3 + 4 int sum = nums.stream().reduce(0, (a, b) -> a + b); System.out.println(sum); // Output: 10