01 / 21

Java Streams
Map / Filter / Reduce

Transform collections with declarative pipelines: select, transform, and aggregate data in a single fluent chain.

Java Programming

What Is a Stream?

A Stream is a sequence of elements that supports functional-style operations to process data. Unlike a collection, a stream does not store data: it pipelines elements from a source through a chain of transformations.

Source filter() map() result Collection Intermediate Intermediate Terminal

Imperative vs Declarative

Traditional loops are imperative: you tell Java how to iterate. Streams are declarative: you describe what you want, and the library handles iteration.

Imperative (loop)
Manually create a list, write a for-loop, add an if-check, and append results one by one.
Declarative (stream)
Chain .stream().filter().map().collect() and let the pipeline do the work in one expression.

The Three Core Operations

map()
Transforms each element into something new. Input size = output size.
filter()
Selects elements matching a condition. Output size ≤ input size.
reduce()
Combines all elements into a single result (sum, max, concatenation).
1 2 3 4 Input: [1, 2, 3, 4]
\( \text{filter}(n \rightarrow n > 1) \)
2 3 4
\( \text{map}(n \rightarrow n \times 10) \)
20 30 40
\( \text{reduce}(0, +) \)
90

The Pipeline Pattern

Every stream pipeline has three stages: a source, zero or more intermediate operations, and exactly one terminal operation.

List<String> result = names.stream() // 1. Source .filter(s -> s.length() > 3) // 2. Intermediate .map(String::toUpperCase) // 2. Intermediate .collect(Collectors.toList()); // 3. Terminal

map(): Transform Every Element

map() applies a function to each element and returns a new stream of the results. The output stream always has the same number of elements as the input.

// Convert a list of names to their lengths List<Integer> lengths = names.stream() .map(String::length) .collect(Collectors.toList()); // ["Alice","Bob","Charlie"] → [5, 3, 7]

filter(): Select Matching Elements

filter() takes a Predicate (a function returning boolean) and keeps only elements for which the predicate returns true.

// Keep only even numbers List<Integer> evens = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); // [1, 2, 3, 4, 5, 6] → [2, 4, 6]

reduce(): Combine Into One

reduce() is the terminal operation that folds all elements into a single result by repeatedly applying a binary operator.

// Sum all numbers int sum = numbers.stream() .reduce(0, (a, b) -> a + b); // [1, 2, 3, 4] → 10 // Equivalent shorthand using method reference int sum2 = numbers.stream() .reduce(0, Integer::sum);

Intermediate vs Terminal

Intermediate Terminal
Returns Stream<\( T \)> Value / Collection
Lazy? Yes: deferred until terminal No: triggers execution
Chainable? Yes: returns a stream No: ends the pipeline
Examples filter, map, sorted, distinct collect, reduce, forEach, count

How to Build a Pipeline

1
Identify the source: call .stream() on a List, Set, array, or other collection.
2
Filter first: narrow down elements early with .filter() to avoid unnecessary work downstream.
3
Transform with map: apply .map() to convert each surviving element into the shape you need.
4
Terminate: end with .collect(), .reduce(), .count(), or another terminal operation to produce your result.

Example 1: Active User Emails

Given a list of User objects, extract the email addresses of all active users and collect them into a list.

List<String> activeEmails = users.stream() .filter(User::isActive) // keep active .map(User::getEmail) // extract email .collect(Collectors.toList()); // gather

Example 2: Sum of Squares

Compute the sum of squares of all positive numbers in a list, combining all three operations in one pipeline.

List<Integer> nums = List.of(-3, -1, 0, 2, 4, 5); int sumOfSquares = nums.stream() .filter(n -> n > 0) // [2, 4, 5] .map(n -> n * n) // [4, 16, 25] .reduce(0, Integer::sum); // 45

Example 3: Longest Word

Find the longest word in a list. This example uses filter to clean data, map to normalize, and a terminal operation to select the max.

List<String> words = List.of("hi", "", "stream", "java", "programming"); Optional<String> longest = words.stream() .filter(w -> !w.isEmpty()) // remove blanks .map(String::toLowerCase) // normalize .max(Comparator.comparingInt(String::length)); longest.ifPresent(System.out::println); // "programming"

Method References: Cleaner Lambdas

When a lambda simply calls an existing method, you can replace it with a method reference for brevity.

Lambda Method Reference
s → s.toUpperCase() String::toUpperCase
s → s.length() String::length
n → Math.abs(n) Math::abs
x → System.out.println(x) System.out::println

Common Mistakes

✕ Reusing a Stream
Calling a terminal op twice on the same stream throws IllegalStateException. Create a new stream each time.
✕ Forgetting Terminal Op
A pipeline with only intermediate ops does nothing: no data flows until you add collect, reduce, forEach, etc.
✕ Modifying Source
Mutating the original collection inside a stream lambda leads to ConcurrentModificationException or unpredictable results.

Quick Reference Table

Operation Type Returns Purpose
filter() Intermediate Stream<\( T \)> Select elements
map() Intermediate Stream<\( R \)> Transform elements
sorted() Intermediate Stream<\( T \)> Order elements
distinct() Intermediate Stream<\( T \)> Remove duplicates
reduce() Terminal \( T \) or Optional<\( T \)> Combine into one
collect() Terminal Collection Gather results
forEach() Terminal void Side effect per item
count() Terminal long Count elements

Question 1 of 5

Which stream operation transforms each element into a new value without changing the number of elements?

Question 2 of 5

What happens if you call two terminal operations on the same stream object?

Question 3 of 5

What is the result of the following stream pipeline?

List<Integer> list = List.of(1, 2, 3, 4, 5); list.stream() .filter(n -> n % 2 == 0) .map(n -> n * 3) .collect(Collectors.toList());

Question 4 of 5

What is the identity value in stream.reduce(0, Integer::sum)?

Question 5 of 5

Which of the following is an intermediate operation?