Module 10 · Lambdas, Streams, Concurrency and JDBC — topic 2 of 5
The Streams API
Processing collections declaratively with streams: creating streams, filter/map/sorted/distinct/limit, terminal operations, collectors for grouping and joining, primitive streams and Optional.
Learning objectives
- Build stream pipelines from collections, arrays and ranges
- Use collectors to group, count, join and partition data
- Use Optional results safely
Definition
A stream is a sequence of elements supporting a pipeline of lazy intermediate operations (filter, map, sorted …) ending in a terminal operation (collect, count, reduce …) that produces a result. Streams do not store data and do not modify their source.
Introduction
Loops say *how* to process data step by step. Streams say *what* you want: 'the names of paid orders over ₹1,000, sorted, as a list'. The result is often shorter and closer to the problem statement, and the same pipeline can even run in parallel.
Why it matters
Streams are used throughout modern Java code bases for reporting, data transformation and API responses.
Grouping and summarising data with collectors replaces many lines of manual map-building code.
Detailed explanation
Sources. collection.stream(), Arrays.stream(array), Stream.of(a, b, c), IntStream.range(0, n) / rangeClosed, Files.lines(path) and Stream.iterate/generate (with limit).
Intermediate operations return a new stream and are lazy — nothing happens until a terminal operation runs: filter, map, flatMap, distinct, sorted, limit, skip, peek, and mapToInt to switch to a primitive stream.
Terminal operations produce a result or side effect: toList() (Java 16), collect(...), forEach, count, sum/average (primitive streams), min/max, reduce, anyMatch/allMatch/noneMatch, findFirst.
Collectors. Collectors.groupingBy(classifier) (optionally with a downstream collector such as counting(), summingInt, averagingDouble or mapping), partitioningBy(predicate), toMap(keyFn, valueFn), joining(", ") and toSet().
Optional. Operations that might find nothing — findFirst, max, min — return Optional<T>. Use orElse, orElseGet, orElseThrow, ifPresent or map rather than calling get() blindly.
Rules. A stream can be consumed only once. Lambdas in a pipeline should not modify shared state or the source collection. Parallel streams (parallelStream()) can speed up large CPU-bound jobs but add overhead for small ones.
Syntax
- Nothing runs until a terminal operation is called.
- A stream can't be reused after its terminal operation.
- toList() returns an unmodifiable list; use collect(Collectors.toList()) for a modifiable one.
Code examples
filter, map, sorted and friends
[144, 144, 400, 64] [1, 3, 5, 7, 8, 12, 20] [20, 12, 12] count > 6: 5, any > 15: true sum 1..100 = 5050 [STREAM, LAMBDA]
Reduce, statistics and Optional
total 372, min 58, max 95, avg 74.4 95 -1 false topper scored 95 1 2 4 8 16 32 64 128 256 512
More examples
Grouping and reporting with collectors
revenue by region: {East=110500.0, North=180000.0, South=61500.0}
units by product: {Desk=5, Laptop=5, Mouse=75}
big: [North/Laptop, East/Laptop] small: [South/Mouse, North/Mouse, South/Desk, East/Mouse]
biggest sale: Laptop in North
ranking: [North, East, South]
all tags: [java, oop, sql, streams]Step-by-step explanation
groupingBy(Sale::region, TreeMap::new, summingDouble(Sale::revenue))groups sales by region into a sorted TreeMap and sums each group's revenue.- A second grouping totals units per product with
summingInt. partitioningBysplits the data into two groups (true/false); the downstreammappingcollector turns each sale into a label.max(...)returns an Optional, whichmaptransforms andorElseunwraps safely.- Streaming over a map's
entrySet()and sorting by value ranks the regions;flatMapflattens nested lists into one stream of tags.
Expected output
Running “Grouping and reporting with collectors” prints exactly:
Practical applications
- Building API responses from database results
- Reports and dashboards: totals, averages and top-N lists
- Data cleaning: filtering, de-duplicating and normalising records
- Processing log files line by line with Files.lines
Best practices
- Keep pipelines readable: one operation per line.
- Prefer collectors over manual map building.
- Use loops when they are clearer, for example with early exits or complex state.
Common mistakes
Reusing a stream
Avoid
Prefer
A stream can be consumed only once; create a new one from the source for each pipeline.
Side effects inside the pipeline
Avoid
Prefer
Mutating external state from a stream is error-prone (and unsafe in parallel); let a terminal operation build the result.
Important notes
- Stream.toList() was added in Java 16; on older versions use collect(Collectors.toList()).
- groupingBy uses a HashMap by default; pass TreeMap::new (as above) when you need sorted, predictable output.
Key takeaways
- A stream pipeline is a source, lazy intermediate operations and one terminal operation.
- Collectors group, count, sum, partition and join data.
- Operations that may find nothing return Optional; unwrap it with orElse or ifPresent.
Try it yourself
- 1From a list of students, find the average marks per branch, sorted by branch.
- 2Find the three most frequent words in a paragraph using streams.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
9 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- ModerateWhat is printed?
- ModerateWhat is printed?