streams: Java Stream API + Collectors cookbook module (creation, laziness and short-circuiting, intermediate/terminal ops, Collectors recipes and toMap traps, primitive stream overflow, parallel traps, Gatherers on JDK 25, loop-to-stream conversion), 12 contract tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b49nGy7tcEjVUa3WAA
This commit is contained in:
Claude
2026-11-24 05:52:24 +05:30
parent 9c2ae10d7f
commit 74da9cd899
28 changed files with 831 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
# streams
Companion code for the ankurm.com post *"Java Stream API Tutorial with Examples + Collectors
Cookbook"* (https://ankurm.com/java-streams-api-complete-guide/). Module in `java-core-examples`,
the Java-core series. There is deliberately no `docs/` folder: the explanations live in the
post itself.
## Versions this was built and tested against
| Component | Version | Notes |
|---|---|---|
| JDK | 25.0.5.1+2 (Temurin, LTS) | `Stream.toList()` is Java 16; `takeWhile`/`dropWhile`/`iterate` with predicate/`ofNullable` are Java 9; `Collectors.filtering`/`flatMapping` are Java 9; `teeing` is Java 12; `mapMulti` is Java 16; Stream Gatherers are final in JDK 24 (JEP 485). |
| JUnit Jupiter | 5.11.0 | |
| Maven | 3.9.11 | |
## Quickstart
```bash
export JAVA_HOME=/path/to/jdk-25
mvn compile
java -cp target/classes com.ankurm.streams.CollectorsCookbookDemo
```
`scripts/run-all.sh` regenerates every file in `output/`. `scripts/run.sh <ClassName>` runs one
demo ad hoc.
## What's in here
| File | What it shows |
|---|---|
| `CreationDemo` | Every common way to obtain a stream. |
| `LazyPipelineDemo` | Nothing runs without a terminal operation; elements flow one at a time; short-circuiting; `count()` skipping `peek`; the single-use `IllegalStateException`. |
| `IntermediateOpsDemo` | `filter`, `map`, `flatMap`, `mapMulti`, `sorted`, `distinct`, `limit`, `skip`, `takeWhile`, `dropWhile`. |
| `TerminalOpsDemo` | `reduce`, the match family, `findFirst`, `Stream.toList()` versus `Collectors.toList()`. |
| `CollectorsCookbookDemo` | `groupingBy` + downstream collectors, `partitioningBy`, `toMap` traps, `filtering`, `flatMapping`, `teeing`. |
| `PrimitiveStreamsDemo` | `IntStream` statistics and the silent `int` overflow. |
| `ParallelDemo` | Associative versus non-associative reduce, shared mutable state, encounter order. |
| `GatherersDemo` | `windowFixed`, `windowSliding`, `scan`, `fold`, `mapConcurrent` and a custom `Gatherer`. |
| `LoopToStreamDemo` | Converting a for loop, and the behaviours that change. |
| `StreamsContractTest` | Pins the claims in the post as assertions (12/12). |
| `output/00-10` | Captured runs; `00` is `javap java.util.stream.Gatherers` straight from the JDK. |
## Non-deterministic output
`ParallelDemo` prints a number that depends on the machine and on thread scheduling: the
parallel result of the non-associative `reduce`, and the final size of the `ArrayList` that
parallel `forEach` wrote into without synchronisation. The committed `output/07-parallel.txt` is
one real run on a 2-vCPU sandbox (common pool parallelism 1); yours will differ.
+8
View File
@@ -0,0 +1,8 @@
Compiled from "Gatherers.java"
public final class java.util.stream.Gatherers {
public static <TR> java.util.stream.Gatherer<TR, ?, java.util.List<TR>> windowFixed(int);
public static <TR> java.util.stream.Gatherer<TR, ?, java.util.List<TR>> windowSliding(int);
public static <T, R> java.util.stream.Gatherer<T, ?, R> fold(java.util.function.Supplier<R>, java.util.function.BiFunction<? super R, ? super T, ? extends R>);
public static <T, R> java.util.stream.Gatherer<T, ?, R> scan(java.util.function.Supplier<R>, java.util.function.BiFunction<? super R, ? super T, ? extends R>);
public static <T, R> java.util.stream.Gatherer<T, ?, R> mapConcurrent(int, java.util.function.Function<? super T, ? extends R>);
}
+12
View File
@@ -0,0 +1,12 @@
collection.stream() : [Alice, Bob, Carol]
Stream.of(1,2,3) : [1, 2, 3]
Arrays.stream(array) : [x, y, z]
IntStream.range(1,6) : [1, 2, 3, 4, 5]
IntStream.rangeClosed : [1, 2, 3, 4, 5]
Stream.iterate(0, n+2) : [0, 2, 4, 6, 8]
iterate(1, <100, *3) : [1, 3, 9, 27, 81]
Stream.generate(...) : [ab, ab, ab]
Stream.ofNullable(null) : []
Optional.stream() : [here]
"a,b,c".split(",") stream : [a, b, c]
"hey".chars() : [104, 101, 121]
+27
View File
@@ -0,0 +1,27 @@
== 1. Nothing runs until a terminal operation ==
pipeline built, nothing printed above this line
now call toList():
peek saw 1
peek saw 2
peek saw 3
== 2. Elements flow one at a time through the whole pipeline ==
after filter: 1
after map : 1
after filter: 3
after map : 9
after filter: 5
after map : 25
== 3. Short-circuiting stops early ==
anyMatch(n > 10) = true, elements touched = 3 of 6
== 4. count() may skip the pipeline entirely ==
count = 3 (no peek lines: the size was known from the source)
peek saw 1
peek saw 2
peek saw 3
count after filter = 3 (filter makes the size unknown, so peek runs)
== 5. A stream is single use ==
IllegalStateException: stream has already been operated upon or closed
+14
View File
@@ -0,0 +1,14 @@
filter even : [2, 4, 6, 8, 10]
map toUpperCase : [HELLO, WORLD, JAVA]
map (no flatten) : [3, 2, 4] <- one result per inner list
flatMap(List::stream): [1, 2, 3, 4, 5, 6, 7, 8, 9]
mapMulti (dup evens): [1, 2, 2, 3, 4, 4]
sorted() : [Alice, Bob, Carol, Dave]
sorted(reverse) : [Dave, Carol, Bob, Alice]
sorted(len, alpha) : [Bob, Dave, Alice, Carol]
distinct() : [1, 2, 3, 4, 5]
limit(4) : [1, 2, 2, 3]
skip(5) : [3, 4, 5]
takeWhile(< 5) : [1, 2, 3]
dropWhile(< 5) : [10, 2, 1]
filter(< 5) : [1, 2, 3, 2, 1] <- not the same thing
+14
View File
@@ -0,0 +1,14 @@
reduce(0, Integer::sum) : 15
reduce((a,b) -> a*b) : Optional[120]
reduce on empty stream : Optional.empty
reduce("", join) : Java Streams are powerful
anyMatch even : true
allMatch positive : true
noneMatch negative : true
allMatch on empty stream : true <- vacuously true
findFirst(n > 5) : Optional[7]
count / min / max : 6 / Optional[1] / Optional[9]
Collectors.toList() then add: [1, 2, 3, 4]
Stream.toList() then add : UnsupportedOperationException
toList() allows null elements: [a, null]
List.of(...) allows null : NullPointerException
+27
View File
@@ -0,0 +1,27 @@
== groupingBy and downstream collectors ==
byCountry : {IN=[Order[customer=ankur, product=laptop, amount=1200.0, country=IN], Order[customer=ankur, product=tablet, amount=400.0, country=IN]], US=[Order[customer=alex, product=phone, amount=800.0, country=US], Order[customer=brian, product=laptop, amount=1500.0, country=US]]}
countByCustomer : {ankur=2, alex=1, brian=1}
revenueByCountry : {IN=1600.0, US=2300.0}
productsByCountry : {IN=[laptop, tablet], US=[phone, laptop]}
topByCountry : {IN=Optional[Order[customer=ankur, product=laptop, amount=1200.0, country=IN]], US=Optional[Order[customer=brian, product=laptop, amount=1500.0, country=US]]}
sorted keys (TreeMap): {IN=2, US=2}
== partitioningBy ==
amount > 1000 : {false=2, true=2}
amount > 5000 : {false=4, true=0} <- both keys present even when one side is empty
groupingBy > 5000 : {false=4} <- only the keys that occurred
== joining, toMap, collectingAndThen ==
customerCsv : [ankur, alex, brian]
toMap w/ merge : {ankur=1600.0, alex=800.0, brian=1500.0}
toMap w/o merge : IllegalStateException: Duplicate key ankur (attempted merging values 1200.0 and 400.0)
toMap null value : NullPointerException
unmodifiable names : [ankur, alex, brian]
== Java 9-12 additions ==
filtering (> 1300) : {IN=0, US=1}
filter then group : {US=1} <- IN disappears: filter removes the element before grouping sees it
flatMapping : {IN=[l, t], US=[p, l]}
summarizingDouble : DoubleSummaryStatistics{count=4, sum=3900.000000, min=400.000000, average=975.000000, max=1500.000000}
teeing (min,max) : MinMax[min=Order[customer=ankur, product=tablet, amount=400.0, country=IN], max=Order[customer=brian, product=laptop, amount=1500.0, country=US]]
teeing (avg) : 975.0
+11
View File
@@ -0,0 +1,11 @@
rangeClosed(1,100).sum() : 5050
summaryStatistics : IntSummaryStatistics{count=8, sum=31, min=1, average=3.875000, max=9}
mapToInt(length).sum() : 17
average of empty IntStream : OptionalDouble.empty
sum of empty IntStream : 0
boxed().toList() : [1, 2, 3]
IntStream sum overflow : -2147483648
asLongStream sum : 2147483648
Math.addExact in long : no overflow
Math.addExact in int : integer overflow
Stream<Integer>.reduce sum : -2147483648 <- also wraps
+15
View File
@@ -0,0 +1,15 @@
parallel sum 1..1_000_000 : 500000500000 <- associative, stateless: safe
== forEach vs forEachOrdered (encounter order) ==
forEachOrdered : 1 2 3 4 5 6 7 8 9 10
parallel ... toList() : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <- order IS preserved by collectors
== non-associative reduce gives a different answer ==
sequential 0-1-2-...-10 : -55
parallel (same lambda) : 15 <- subtraction is not associative
== shared mutable state ==
ArrayList.add from forEach : size 196740 (expected 200000) <- lost or duplicated writes are possible
collect/toList instead : size 200000
Common pool parallelism : 1
+7
View File
@@ -0,0 +1,7 @@
windowFixed(3) : [[1, 2, 3], [4, 5, 6], [7]]
windowSliding(3) : [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
scan (running sum) : [1, 3, 6, 10, 15, 21, 28]
fold (one result) : [28]
mapConcurrent(2) : [10, 20, 30, 40, 50, 60, 70]
3-point moving avg : [2.0, 3.0, 4.0, 5.0, 6.0]
dedupeAdjacent : [1, 2, 1, 3] <- distinct() would give [1, 2, 3]
+17
View File
@@ -0,0 +1,17 @@
== 1. The straightforward conversion ==
loop : {IN=1200.0, US=2300.0}
stream : {IN=1200.0, US=2300.0}
equal : true
== 2. A loop with break becomes findFirst, not filter ==
loop : ankur/laptop
stream : ankur/laptop
== 3. The list a loop built was mutable; toList() is not ==
loop list after add : [ankur, alex, brian, ankur, extra]
stream list after add : UnsupportedOperationException
== 4. A loop can update a counter; a lambda cannot ==
works, but it is a side effect: 2
the pipeline way (count) : 2
(a plain `int hits` would not compile: lambdas capture effectively-final variables only)
+4
View File
@@ -0,0 +1,4 @@
-------------------------------------------------------------------------------
Test set: com.ankurm.streams.StreamsContractTest
-------------------------------------------------------------------------------
Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.122 s -- in com.ankurm.streams.StreamsContractTest
+43
View File
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ankurm</groupId>
<artifactId>java-core-examples</artifactId>
<version>1.0</version>
</parent>
<artifactId>streams</artifactId>
<name>streams</name>
<description>Java Stream API end to end: pipeline laziness, intermediate and terminal operations, the Collectors cookbook, primitive streams, parallel-stream traps and Stream Gatherers (final in JDK 24).</description>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<release>25</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>
</project>
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
NOISE='JAVA_TOOL_OPTIONS|_JAVA_OPTIONS|Djavax\.net\.ssl|^WARNING'
javap java.util.stream.Gatherers 2>&1 | grep -vE "$NOISE" > output/00-javap-gatherers.txt
mvn -q -B compile
i=1
for d in CreationDemo LazyPipelineDemo IntermediateOpsDemo TerminalOpsDemo CollectorsCookbookDemo PrimitiveStreamsDemo ParallelDemo GatherersDemo LoopToStreamDemo; do
f=$(printf 'output/%02d-%s.txt' "$i" "$(echo "$d" | sed 's/Demo$//' | tr 'A-Z' 'a-z')")
java -cp target/classes "com.ankurm.streams.$d" 2>&1 | grep -vE "$NOISE" > "$f"
i=$((i+1))
done
mvn -q -B test
cp target/surefire-reports/com.ankurm.streams.StreamsContractTest.txt output/10-contract-test.txt
echo "Regenerated output/00-10."
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Run one demo class ad hoc, e.g.: ./scripts/run.sh GatherersDemo
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -q -B compile
java -cp target/classes "com.ankurm.streams.$1"
@@ -0,0 +1,73 @@
package com.ankurm.streams;
import static java.util.stream.Collectors.*;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
/** The Collectors patterns used most often, all on the same four orders. */
public class CollectorsCookbookDemo {
public static void main(String[] args) {
List<Order> orders = Order.sample();
System.out.println("== groupingBy and downstream collectors ==");
Map<String, List<Order>> byCountry = orders.stream().collect(groupingBy(Order::country));
System.out.println("byCountry : " + byCountry);
System.out.println("countByCustomer : " + orders.stream().collect(groupingBy(Order::customer, counting())));
System.out.println("revenueByCountry : " + orders.stream().collect(groupingBy(Order::country, summingDouble(Order::amount))));
System.out.println("productsByCountry : " + orders.stream()
.collect(groupingBy(Order::country, mapping(Order::product, toList()))));
Map<String, Optional<Order>> topByCountry = orders.stream()
.collect(groupingBy(Order::country, maxBy(Comparator.comparingDouble(Order::amount))));
System.out.println("topByCountry : " + topByCountry);
System.out.println("sorted keys (TreeMap): " + orders.stream()
.collect(groupingBy(Order::country, TreeMap::new, counting())));
System.out.println();
System.out.println("== partitioningBy ==");
System.out.println("amount > 1000 : " + orders.stream().collect(partitioningBy(o -> o.amount() > 1000, counting())));
System.out.println("amount > 5000 : " + orders.stream().collect(partitioningBy(o -> o.amount() > 5000, counting()))
+ " <- both keys present even when one side is empty");
System.out.println("groupingBy > 5000 : " + orders.stream().collect(groupingBy(o -> o.amount() > 5000, counting()))
+ " <- only the keys that occurred");
System.out.println();
System.out.println("== joining, toMap, collectingAndThen ==");
System.out.println("customerCsv : " + orders.stream().map(Order::customer).distinct().collect(joining(", ", "[", "]")));
System.out.println("toMap w/ merge : " + orders.stream()
.collect(toMap(Order::customer, Order::amount, Double::sum)));
try {
orders.stream().collect(toMap(Order::customer, Order::amount));
} catch (IllegalStateException e) {
System.out.println("toMap w/o merge : IllegalStateException: " + e.getMessage());
}
try {
orders.stream().collect(toMap(Order::customer, o -> (String) null, (a, b) -> a));
} catch (NullPointerException e) {
System.out.println("toMap null value : NullPointerException");
}
System.out.println("unmodifiable names : " + orders.stream().map(Order::customer).distinct()
.collect(collectingAndThen(toList(), List::copyOf)));
System.out.println();
System.out.println("== Java 9-12 additions ==");
System.out.println("filtering (> 1300) : " + orders.stream()
.collect(groupingBy(Order::country, filtering(o -> o.amount() > 1300, counting()))));
System.out.println("filter then group : " + orders.stream()
.filter(o -> o.amount() > 1300).collect(groupingBy(Order::country, counting()))
+ " <- IN disappears: filter removes the element before grouping sees it");
System.out.println("flatMapping : " + orders.stream()
.collect(groupingBy(Order::country, flatMapping(o -> o.product().chars().mapToObj(c -> (char) c).limit(1), toList()))));
System.out.println("summarizingDouble : " + orders.stream().collect(summarizingDouble(Order::amount)));
record MinMax(Order min, Order max) {}
System.out.println("teeing (min,max) : " + orders.stream().collect(teeing(
minBy(Comparator.comparingDouble(Order::amount)),
maxBy(Comparator.comparingDouble(Order::amount)),
(lo, hi) -> new MinMax(lo.orElseThrow(), hi.orElseThrow()))));
System.out.println("teeing (avg) : " + orders.stream().collect(teeing(
summingDouble(Order::amount), counting(), (total, n) -> total / n)));
}
}
@@ -0,0 +1,29 @@
package com.ankurm.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/** Every common way to get a Stream, and what each one is for. */
public class CreationDemo {
public static void main(String[] args) {
List<String> names = List.of("Alice", "Bob", "Carol");
System.out.println("collection.stream() : " + names.stream().toList());
System.out.println("Stream.of(1,2,3) : " + Stream.of(1, 2, 3).toList());
System.out.println("Arrays.stream(array) : " + Arrays.stream(new String[] {"x", "y", "z"}).toList());
System.out.println("IntStream.range(1,6) : " + IntStream.range(1, 6).boxed().toList());
System.out.println("IntStream.rangeClosed : " + IntStream.rangeClosed(1, 5).boxed().toList());
System.out.println("Stream.iterate(0, n+2) : " + Stream.iterate(0, n -> n + 2).limit(5).toList());
// Java 9+: iterate with a hasNext predicate is a stream-shaped for loop.
System.out.println("iterate(1, <100, *3) : " + Stream.iterate(1, n -> n < 100, n -> n * 3).toList());
System.out.println("Stream.generate(...) : " + Stream.generate(() -> "ab").limit(3).toList());
// Java 9+: ofNullable gives an empty stream for null instead of an NPE.
String maybe = null;
System.out.println("Stream.ofNullable(null) : " + Stream.ofNullable(maybe).toList());
System.out.println("Optional.stream() : " + Optional.of("here").stream().toList());
System.out.println("\"a,b,c\".split(\",\") stream : " + Arrays.stream("a,b,c".split(",")).toList());
System.out.println("\"hey\".chars() : " + "hey".chars().boxed().toList());
}
}
@@ -0,0 +1,38 @@
package com.ankurm.streams;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Gatherer;
import java.util.stream.Gatherers;
import java.util.stream.Stream;
/** Stream Gatherers (JEP 485, final in JDK 24): the intermediate operations Stream itself does not have. */
public class GatherersDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7);
System.out.println("windowFixed(3) : " + nums.stream().gather(Gatherers.windowFixed(3)).toList());
System.out.println("windowSliding(3) : " + nums.stream().gather(Gatherers.windowSliding(3)).toList());
System.out.println("scan (running sum) : " + nums.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
System.out.println("fold (one result) : " + nums.stream().gather(Gatherers.fold(() -> 0, Integer::sum)).toList());
System.out.println("mapConcurrent(2) : " + nums.stream().gather(Gatherers.mapConcurrent(2, n -> n * 10)).toList());
// A moving average is windowSliding plus a map: one line that used to need a hand-written Spliterator.
List<Double> moving = nums.stream().gather(Gatherers.windowSliding(3))
.map(w -> w.stream().mapToInt(Integer::intValue).average().orElse(0)).toList();
System.out.println("3-point moving avg : " + moving);
// A custom gatherer: emit each element only if it differs from the previous one.
Supplier<int[]> lastSeen = () -> new int[] {Integer.MIN_VALUE};
Gatherer<Integer, int[], Integer> dedupeAdjacent = Gatherer.ofSequential(
lastSeen,
(state, element, downstream) -> {
if (element != state[0]) {
state[0] = element;
return downstream.push(element);
}
return true;
});
System.out.println("dedupeAdjacent : " + Stream.of(1, 1, 2, 2, 2, 1, 3, 3).gather(dedupeAdjacent).toList()
+ " <- distinct() would give [1, 2, 3]");
}
}
@@ -0,0 +1,41 @@
package com.ankurm.streams;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
/** Each intermediate operation with its result. */
public class IntermediateOpsDemo {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("filter even : " + numbers.stream().filter(n -> n % 2 == 0).toList());
List<String> words = List.of("hello", "world", "java");
System.out.println("map toUpperCase : " + words.stream().map(String::toUpperCase).toList());
List<List<Integer>> nested = List.of(List.of(1, 2, 3), List.of(4, 5), List.of(6, 7, 8, 9));
System.out.println("map (no flatten) : " + nested.stream().map(List::size).toList() + " <- one result per inner list");
System.out.println("flatMap(List::stream): " + nested.stream().flatMap(List::stream).toList());
// Java 16+: mapMulti emits zero, one or many outputs per input without building a Stream per element.
System.out.println("mapMulti (dup evens): " + Stream.of(1, 2, 3, 4)
.<Integer>mapMulti((n, sink) -> { sink.accept(n); if (n % 2 == 0) sink.accept(n); }).toList());
List<String> names = List.of("Carol", "Alice", "Bob", "Dave");
System.out.println("sorted() : " + names.stream().sorted().toList());
System.out.println("sorted(reverse) : " + names.stream().sorted(Comparator.reverseOrder()).toList());
System.out.println("sorted(len, alpha) : " + names.stream()
.sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())).toList());
List<Integer> nums = List.of(1, 2, 2, 3, 3, 3, 4, 5);
System.out.println("distinct() : " + nums.stream().distinct().toList());
System.out.println("limit(4) : " + nums.stream().limit(4).toList());
System.out.println("skip(5) : " + nums.stream().skip(5).toList());
// Java 9+: takeWhile / dropWhile work on a prefix, filter works on everything.
List<Integer> mixed = List.of(1, 2, 3, 10, 2, 1);
System.out.println("takeWhile(< 5) : " + mixed.stream().takeWhile(n -> n < 5).toList());
System.out.println("dropWhile(< 5) : " + mixed.stream().dropWhile(n -> n < 5).toList());
System.out.println("filter(< 5) : " + mixed.stream().filter(n -> n < 5).toList() + " <- not the same thing");
}
}
@@ -0,0 +1,55 @@
package com.ankurm.streams;
import java.util.List;
import java.util.stream.Stream;
/** Laziness, per-element flow, short-circuiting and the single-use rule. */
public class LazyPipelineDemo {
public static void main(String[] args) {
System.out.println("== 1. Nothing runs until a terminal operation ==");
Stream<Integer> lazy = List.of(1, 2, 3).stream()
.peek(n -> System.out.println(" peek saw " + n));
System.out.println("pipeline built, nothing printed above this line");
System.out.println("now call toList():");
lazy.toList();
System.out.println();
System.out.println("== 2. Elements flow one at a time through the whole pipeline ==");
List.of(1, 2, 3, 4, 5).stream()
.filter(n -> n % 2 != 0)
.peek(n -> System.out.println(" after filter: " + n))
.map(n -> n * n)
.peek(n -> System.out.println(" after map : " + n))
.toList();
System.out.println();
System.out.println("== 3. Short-circuiting stops early ==");
int[] touched = {0};
boolean found = Stream.of(5, 8, 12, 3, 9, 20)
.peek(n -> touched[0]++)
.anyMatch(n -> n > 10);
System.out.println("anyMatch(n > 10) = " + found + ", elements touched = " + touched[0] + " of 6");
System.out.println();
System.out.println("== 4. count() may skip the pipeline entirely ==");
long n = List.of(1, 2, 3).stream()
.peek(x -> System.out.println(" peek saw " + x))
.count();
System.out.println("count = " + n + " (no peek lines: the size was known from the source)");
long n2 = List.of(1, 2, 3).stream()
.filter(x -> x > 0)
.peek(x -> System.out.println(" peek saw " + x))
.count();
System.out.println("count after filter = " + n2 + " (filter makes the size unknown, so peek runs)");
System.out.println();
System.out.println("== 5. A stream is single use ==");
Stream<String> s = Stream.of("a", "b");
s.toList();
try {
s.toList();
} catch (IllegalStateException e) {
System.out.println("IllegalStateException: " + e.getMessage());
}
}
}
@@ -0,0 +1,68 @@
package com.ankurm.streams;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingDouble;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
/** Turning a for loop into a pipeline, and the three behaviours that quietly change when you do. */
public class LoopToStreamDemo {
public static void main(String[] args) {
List<Order> orders = Order.sample();
System.out.println("== 1. The straightforward conversion ==");
Map<String, Double> loopRevenue = new TreeMap<>();
for (Order o : orders) {
if (o.amount() >= 500) {
loopRevenue.merge(o.country(), o.amount(), Double::sum);
}
}
Map<String, Double> streamRevenue = orders.stream()
.filter(o -> o.amount() >= 500)
.collect(groupingBy(Order::country, TreeMap::new, summingDouble(Order::amount)));
System.out.println("loop : " + loopRevenue);
System.out.println("stream : " + streamRevenue);
System.out.println("equal : " + loopRevenue.equals(streamRevenue));
System.out.println();
System.out.println("== 2. A loop with break becomes findFirst, not filter ==");
Order firstBig = null;
for (Order o : orders) {
if (o.amount() > 1000) {
firstBig = o;
break;
}
}
Optional<Order> viaStream = orders.stream().filter(o -> o.amount() > 1000).findFirst();
System.out.println("loop : " + firstBig.customer() + "/" + firstBig.product());
System.out.println("stream : " + viaStream.map(o -> o.customer() + "/" + o.product()).orElse("none"));
System.out.println();
System.out.println("== 3. The list a loop built was mutable; toList() is not ==");
List<String> loopNames = new ArrayList<>();
for (Order o : orders) {
loopNames.add(o.customer());
}
loopNames.add("extra");
System.out.println("loop list after add : " + loopNames);
List<String> streamNames = orders.stream().map(Order::customer).toList();
try {
streamNames.add("extra");
} catch (UnsupportedOperationException e) {
System.out.println("stream list after add : UnsupportedOperationException");
}
System.out.println();
System.out.println("== 4. A loop can update a counter; a lambda cannot ==");
int[] hits = {0};
orders.stream().filter(o -> o.country().equals("US")).forEach(o -> hits[0]++);
System.out.println("works, but it is a side effect: " + hits[0]);
long clean = orders.stream().filter(o -> o.country().equals("US")).count();
System.out.println("the pipeline way (count) : " + clean);
System.out.println("(a plain `int hits` would not compile: lambdas capture effectively-final variables only)");
}
}
@@ -0,0 +1,15 @@
package com.ankurm.streams;
import java.util.List;
/** The one data set every Collectors example in this module (and the post) runs against. */
public record Order(String customer, String product, double amount, String country) {
public static List<Order> sample() {
return List.of(
new Order("ankur", "laptop", 1200, "IN"),
new Order("alex", "phone", 800, "US"),
new Order("brian", "laptop", 1500, "US"),
new Order("ankur", "tablet", 400, "IN"));
}
}
@@ -0,0 +1,45 @@
package com.ankurm.streams;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
/** What changes (and what silently breaks) when you add .parallel(). */
public class ParallelDemo {
public static void main(String[] args) {
System.out.println("parallel sum 1..1_000_000 : "
+ LongStream.rangeClosed(1, 1_000_000L).parallel().sum() + " <- associative, stateless: safe");
System.out.println();
System.out.println("== forEach vs forEachOrdered (encounter order) ==");
StringBuilder a = new StringBuilder();
IntStream.rangeClosed(1, 10).parallel().forEachOrdered(n -> a.append(n).append(' '));
System.out.println("forEachOrdered : " + a.toString().trim());
List<Integer> viaToList = IntStream.rangeClosed(1, 10).parallel().boxed().toList();
System.out.println("parallel ... toList() : " + viaToList + " <- order IS preserved by collectors");
System.out.println();
System.out.println("== non-associative reduce gives a different answer ==");
int seq = IntStream.rangeClosed(1, 10).boxed().reduce(0, (x, y) -> x - y);
int par = IntStream.rangeClosed(1, 10).boxed().parallel().reduce(0, (x, y) -> x - y);
System.out.println("sequential 0-1-2-...-10 : " + seq);
System.out.println("parallel (same lambda) : " + par + " <- subtraction is not associative");
System.out.println();
System.out.println("== shared mutable state ==");
int total = 200_000;
List<Integer> unsafe = new ArrayList<>();
try {
IntStream.range(0, total).parallel().forEach(unsafe::add);
System.out.println("ArrayList.add from forEach : size " + unsafe.size() + " (expected " + total
+ ") <- lost or duplicated writes are possible");
} catch (RuntimeException e) {
System.out.println("ArrayList.add from forEach : " + e.getClass().getSimpleName() + " (list corrupted mid-run)");
}
List<Integer> safe = IntStream.range(0, total).parallel().boxed().toList();
System.out.println("collect/toList instead : size " + safe.size());
System.out.println();
System.out.println("Common pool parallelism : " + java.util.concurrent.ForkJoinPool.commonPool().getParallelism());
}
}
@@ -0,0 +1,38 @@
package com.ankurm.streams;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/** IntStream and friends: no boxing, and a few methods the object stream lacks. */
public class PrimitiveStreamsDemo {
public static void main(String[] args) {
System.out.println("rangeClosed(1,100).sum() : " + IntStream.rangeClosed(1, 100).sum());
IntSummaryStatistics st = IntStream.of(3, 1, 4, 1, 5, 9, 2, 6).summaryStatistics();
System.out.println("summaryStatistics : " + st);
List<String> words = List.of("hello", "world", "streams");
System.out.println("mapToInt(length).sum() : " + words.stream().mapToInt(String::length).sum());
System.out.println("average of empty IntStream : " + IntStream.empty().average());
System.out.println("sum of empty IntStream : " + IntStream.empty().sum());
System.out.println("boxed().toList() : " + IntStream.of(3, 1, 2).sorted().boxed().toList());
// Overflow: IntStream.sum() wraps silently. LongStream does not, until you pass Long.MAX_VALUE.
System.out.println("IntStream sum overflow : " + IntStream.of(Integer.MAX_VALUE, 1).sum());
System.out.println("asLongStream sum : " + IntStream.of(Integer.MAX_VALUE, 1).asLongStream().sum());
try {
IntStream.of(Integer.MAX_VALUE, 1).mapToLong(i -> i).reduce(0L, Math::addExact);
System.out.println("Math.addExact in long : no overflow");
} catch (ArithmeticException e) {
System.out.println("Math.addExact : " + e.getMessage());
}
try {
IntStream.of(Integer.MAX_VALUE, 1).reduce(0, Math::addExact);
} catch (ArithmeticException e) {
System.out.println("Math.addExact in int : " + e.getMessage());
}
System.out.println("Stream<Integer>.reduce sum : " + Stream.of(Integer.MAX_VALUE, 1).reduce(0, Integer::sum) + " <- also wraps");
}
}
@@ -0,0 +1,50 @@
package com.ankurm.streams;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Terminal operations, and the mutable-versus-unmodifiable list question. */
public class TerminalOpsDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5);
int sum = nums.stream().reduce(0, Integer::sum);
System.out.println("reduce(0, Integer::sum) : " + sum);
System.out.println("reduce((a,b) -> a*b) : " + nums.stream().reduce((a, b) -> a * b));
System.out.println("reduce on empty stream : " + Stream.<Integer>empty().reduce(Integer::sum));
System.out.println("reduce(\"\", join) : " + Stream.of("Java", "Streams", "are", "powerful")
.reduce("", (a, b) -> a.isEmpty() ? b : a + " " + b));
List<Integer> data = List.of(3, 7, 1, 9, 4, 6);
System.out.println("anyMatch even : " + data.stream().anyMatch(n -> n % 2 == 0));
System.out.println("allMatch positive : " + data.stream().allMatch(n -> n > 0));
System.out.println("noneMatch negative : " + data.stream().noneMatch(n -> n < 0));
System.out.println("allMatch on empty stream : " + Stream.<Integer>empty().allMatch(n -> n > 100) + " <- vacuously true");
System.out.println("findFirst(n > 5) : " + data.stream().filter(n -> n > 5).findFirst());
System.out.println("count / min / max : " + data.stream().count() + " / "
+ data.stream().min(Integer::compare) + " / " + data.stream().max(Integer::compare));
// toList() vs Collectors.toList(): the difference that surprises people.
List<Integer> unmodifiable = Stream.of(1, 2, 3).toList();
List<Integer> mutable = Stream.of(1, 2, 3).collect(Collectors.toList());
mutable.add(4);
System.out.println("Collectors.toList() then add: " + mutable);
try {
unmodifiable.add(4);
} catch (UnsupportedOperationException e) {
System.out.println("Stream.toList() then add : UnsupportedOperationException");
}
System.out.println("toList() allows null elements: " + Stream.of("a", null).toList());
System.out.println("List.of(...) allows null : "
+ tryNull());
}
private static String tryNull() {
try {
return List.of("a", null).toString();
} catch (NullPointerException e) {
return "NullPointerException";
}
}
}
@@ -0,0 +1,106 @@
package com.ankurm.streams;
import static java.util.stream.Collectors.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Gatherers;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
/** Pins every claim the post makes about behaviour. If one of these fails, the post is wrong. */
class StreamsContractTest {
@Test
void nothingRunsWithoutTerminalOperation() {
AtomicInteger calls = new AtomicInteger();
Stream<Integer> s = Stream.of(1, 2, 3).peek(n -> calls.incrementAndGet());
assertEquals(0, calls.get());
s.toList();
assertEquals(3, calls.get());
}
@Test
void streamIsSingleUse() {
Stream<String> s = Stream.of("a");
s.toList();
IllegalStateException e = assertThrows(IllegalStateException.class, s::toList);
assertEquals("stream has already been operated upon or closed", e.getMessage());
}
@Test
void anyMatchShortCircuits() {
AtomicInteger touched = new AtomicInteger();
assertTrue(Stream.of(5, 8, 12, 3, 9, 20).peek(n -> touched.incrementAndGet()).anyMatch(n -> n > 10));
assertEquals(3, touched.get());
}
@Test
void countSkipsPeekWhenSizeIsKnown() {
AtomicInteger calls = new AtomicInteger();
assertEquals(3, List.of(1, 2, 3).stream().peek(n -> calls.incrementAndGet()).count());
assertEquals(0, calls.get());
assertEquals(3, List.of(1, 2, 3).stream().filter(n -> n > 0).peek(n -> calls.incrementAndGet()).count());
assertEquals(3, calls.get());
}
@Test
void streamToListIsUnmodifiableButCollectorsToListIsNot() {
assertThrows(UnsupportedOperationException.class, () -> Stream.of(1).toList().add(2));
assertDoesNotThrow(() -> Stream.of(1).collect(toList()).add(2));
}
@Test
void toMapWithoutMergeThrowsOnDuplicateKey() {
assertThrows(IllegalStateException.class,
() -> Order.sample().stream().collect(toMap(Order::customer, Order::amount)));
assertEquals(Map.of("ankur", 1600.0, "alex", 800.0, "brian", 1500.0),
Order.sample().stream().collect(toMap(Order::customer, Order::amount, Double::sum)));
}
@Test
void partitioningByAlwaysHasBothKeysGroupingByDoesNot() {
Map<Boolean, Long> p = Order.sample().stream().collect(partitioningBy(o -> o.amount() > 5000, counting()));
Map<Boolean, Long> g = Order.sample().stream().collect(groupingBy(o -> o.amount() > 5000, counting()));
assertEquals(Map.of(false, 4L, true, 0L), p);
assertEquals(Map.of(false, 4L), g);
}
@Test
void filteringDownstreamKeepsEmptyGroupsFilterBeforeDoesNot() {
var down = Order.sample().stream().collect(groupingBy(Order::country, filtering(o -> o.amount() > 1300, counting())));
var before = Order.sample().stream().filter(o -> o.amount() > 1300).collect(groupingBy(Order::country, counting()));
assertEquals(Map.of("IN", 0L, "US", 1L), down);
assertEquals(Map.of("US", 1L), before);
}
@Test
void takeWhileIsPrefixOnlyFilterIsNot() {
List<Integer> mixed = List.of(1, 2, 3, 10, 2, 1);
assertEquals(List.of(1, 2, 3), mixed.stream().takeWhile(n -> n < 5).toList());
assertEquals(List.of(1, 2, 3, 2, 1), mixed.stream().filter(n -> n < 5).toList());
}
@Test
void intStreamSumOverflowsSilently() {
assertEquals(Integer.MIN_VALUE, IntStream.of(Integer.MAX_VALUE, 1).sum());
assertEquals(2147483648L, IntStream.of(Integer.MAX_VALUE, 1).asLongStream().sum());
}
@Test
void gatherersWindowsScanAndFold() {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7);
assertEquals(List.of(List.of(1, 2, 3), List.of(4, 5, 6), List.of(7)), nums.stream().gather(Gatherers.windowFixed(3)).toList());
assertEquals(5, nums.stream().gather(Gatherers.windowSliding(3)).count());
assertEquals(List.of(1, 3, 6, 10, 15, 21, 28), nums.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
assertEquals(List.of(28), nums.stream().gather(Gatherers.fold(() -> 0, Integer::sum)).toList());
}
@Test
void parallelToListKeepsEncounterOrder() {
assertEquals(IntStream.range(0, 1000).boxed().toList(), IntStream.range(0, 1000).parallel().boxed().toList());
}
}