Lab 02: Streams & Lambdas

Objective

Master the Java Streams API: filter, map, flatMap, reduce, collect, groupingBy, partitioningBy, parallel streams, and the Collectors utility class for data aggregation.

Background

The Streams API (Java 8+) brings functional programming to Java. A stream is a sequence of elements from a data source that supports aggregate operations. Streams are lazy — intermediate operations don't execute until a terminal operation is invoked — enabling efficient pipelines that process only what's needed.

Time

30 minutes

Prerequisites

  • Lab 01 (Generics & Collections)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Step 1: The Stream Pipeline

💡 Streams are lazy. filter(), map(), flatMap() are intermediate operations — they create a new stream descriptor but process nothing. Only terminal operations (collect, toList, count, sum, forEach, reduce) trigger execution. This means .filter(expensive).findFirst() stops as soon as the first match is found, not after scanning the whole list.

📸 Verified Output:


Steps 2–8: partitioningBy, teeing, custom collectors, flatMap, reduce, parallel, Capstone

📸 Verified Output:


Summary

Operation
Type
Returns
Use for

filter

Intermediate

Stream<T>

Conditional inclusion

map

Intermediate

Stream<R>

Transform each element

flatMap

Intermediate

Stream<R>

Flatten nested collections

sorted

Intermediate

Stream<T>

Order elements

peek

Intermediate

Stream<T>

Debug without modifying

collect

Terminal

R

Build result container

reduce

Terminal

Optional<T>

Aggregate to single value

count

Terminal

long

Count elements

Further Reading

Last updated