From 74da9cd89955b90c25c06b90593ecfd7d33757e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 05:52:18 +0530 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017ic4b49nGy7tcEjVUa3WAA --- README.md | 1 + pom.xml | 1 + streams/README.md | 48 ++++++++ streams/output/00-javap-gatherers.txt | 8 ++ streams/output/01-creation.txt | 12 ++ streams/output/02-lazypipeline.txt | 27 +++++ streams/output/03-intermediateops.txt | 14 +++ streams/output/04-terminalops.txt | 14 +++ streams/output/05-collectorscookbook.txt | 27 +++++ streams/output/06-primitivestreams.txt | 11 ++ streams/output/07-parallel.txt | 15 +++ streams/output/08-gatherers.txt | 7 ++ streams/output/09-looptostream.txt | 17 +++ streams/output/10-contract-test.txt | 4 + streams/pom.xml | 43 +++++++ streams/scripts/run-all.sh | 18 +++ streams/scripts/run.sh | 6 + .../streams/CollectorsCookbookDemo.java | 73 ++++++++++++ .../java/com/ankurm/streams/CreationDemo.java | 29 +++++ .../com/ankurm/streams/GatherersDemo.java | 38 +++++++ .../ankurm/streams/IntermediateOpsDemo.java | 41 +++++++ .../com/ankurm/streams/LazyPipelineDemo.java | 55 +++++++++ .../com/ankurm/streams/LoopToStreamDemo.java | 68 +++++++++++ .../main/java/com/ankurm/streams/Order.java | 15 +++ .../java/com/ankurm/streams/ParallelDemo.java | 45 ++++++++ .../ankurm/streams/PrimitiveStreamsDemo.java | 38 +++++++ .../com/ankurm/streams/TerminalOpsDemo.java | 50 +++++++++ .../ankurm/streams/StreamsContractTest.java | 106 ++++++++++++++++++ 28 files changed, 831 insertions(+) create mode 100644 streams/README.md create mode 100644 streams/output/00-javap-gatherers.txt create mode 100644 streams/output/01-creation.txt create mode 100644 streams/output/02-lazypipeline.txt create mode 100644 streams/output/03-intermediateops.txt create mode 100644 streams/output/04-terminalops.txt create mode 100644 streams/output/05-collectorscookbook.txt create mode 100644 streams/output/06-primitivestreams.txt create mode 100644 streams/output/07-parallel.txt create mode 100644 streams/output/08-gatherers.txt create mode 100644 streams/output/09-looptostream.txt create mode 100644 streams/output/10-contract-test.txt create mode 100644 streams/pom.xml create mode 100755 streams/scripts/run-all.sh create mode 100755 streams/scripts/run.sh create mode 100644 streams/src/main/java/com/ankurm/streams/CollectorsCookbookDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/CreationDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/GatherersDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/IntermediateOpsDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/LazyPipelineDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/LoopToStreamDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/Order.java create mode 100644 streams/src/main/java/com/ankurm/streams/ParallelDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/PrimitiveStreamsDemo.java create mode 100644 streams/src/main/java/com/ankurm/streams/TerminalOpsDemo.java create mode 100644 streams/src/test/java/com/ankurm/streams/StreamsContractTest.java diff --git a/README.md b/README.md index 665084c..f6bbaab 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ article; each module's own README has that article's version table, quickstart, | [`parallel-streams`](parallel-streams/) | Java Parallel Streams: When They're Slower (JMH Benchmarks and the Common Pool) | | [`random`](random/) | Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator in Java | | [`completablefuture`](completablefuture/) | CompletableFuture in Java: thenApply vs thenCompose, allOf, Exceptions and Timeouts (and When Virtual Threads Win) | +| [`streams`](streams/) | Java Stream API Tutorial with Examples + Collectors Cookbook (laziness, collectors, primitive and parallel streams, Gatherers) | ## License diff --git a/pom.xml b/pom.xml index a3bc0ef..afa2a43 100644 --- a/pom.xml +++ b/pom.xml @@ -44,6 +44,7 @@ parallel-streams random completablefuture + streams diff --git a/streams/README.md b/streams/README.md new file mode 100644 index 0000000..e61d377 --- /dev/null +++ b/streams/README.md @@ -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 ` 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. diff --git a/streams/output/00-javap-gatherers.txt b/streams/output/00-javap-gatherers.txt new file mode 100644 index 0000000..cdfad72 --- /dev/null +++ b/streams/output/00-javap-gatherers.txt @@ -0,0 +1,8 @@ +Compiled from "Gatherers.java" +public final class java.util.stream.Gatherers { + public static java.util.stream.Gatherer> windowFixed(int); + public static java.util.stream.Gatherer> windowSliding(int); + public static java.util.stream.Gatherer fold(java.util.function.Supplier, java.util.function.BiFunction); + public static java.util.stream.Gatherer scan(java.util.function.Supplier, java.util.function.BiFunction); + public static java.util.stream.Gatherer mapConcurrent(int, java.util.function.Function); +} diff --git a/streams/output/01-creation.txt b/streams/output/01-creation.txt new file mode 100644 index 0000000..453e4a3 --- /dev/null +++ b/streams/output/01-creation.txt @@ -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] diff --git a/streams/output/02-lazypipeline.txt b/streams/output/02-lazypipeline.txt new file mode 100644 index 0000000..c70d7b6 --- /dev/null +++ b/streams/output/02-lazypipeline.txt @@ -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 diff --git a/streams/output/03-intermediateops.txt b/streams/output/03-intermediateops.txt new file mode 100644 index 0000000..0b4a7a2 --- /dev/null +++ b/streams/output/03-intermediateops.txt @@ -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 diff --git a/streams/output/04-terminalops.txt b/streams/output/04-terminalops.txt new file mode 100644 index 0000000..2c45792 --- /dev/null +++ b/streams/output/04-terminalops.txt @@ -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 diff --git a/streams/output/05-collectorscookbook.txt b/streams/output/05-collectorscookbook.txt new file mode 100644 index 0000000..80bd98c --- /dev/null +++ b/streams/output/05-collectorscookbook.txt @@ -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 diff --git a/streams/output/06-primitivestreams.txt b/streams/output/06-primitivestreams.txt new file mode 100644 index 0000000..f98810a --- /dev/null +++ b/streams/output/06-primitivestreams.txt @@ -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.reduce sum : -2147483648 <- also wraps diff --git a/streams/output/07-parallel.txt b/streams/output/07-parallel.txt new file mode 100644 index 0000000..710ee5a --- /dev/null +++ b/streams/output/07-parallel.txt @@ -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 diff --git a/streams/output/08-gatherers.txt b/streams/output/08-gatherers.txt new file mode 100644 index 0000000..66701a5 --- /dev/null +++ b/streams/output/08-gatherers.txt @@ -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] diff --git a/streams/output/09-looptostream.txt b/streams/output/09-looptostream.txt new file mode 100644 index 0000000..aec6ff1 --- /dev/null +++ b/streams/output/09-looptostream.txt @@ -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) diff --git a/streams/output/10-contract-test.txt b/streams/output/10-contract-test.txt new file mode 100644 index 0000000..446494d --- /dev/null +++ b/streams/output/10-contract-test.txt @@ -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 diff --git a/streams/pom.xml b/streams/pom.xml new file mode 100644 index 0000000..ee968b6 --- /dev/null +++ b/streams/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + + com.ankurm + java-core-examples + 1.0 + + + streams + streams + 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). + + + + org.junit.jupiter + junit-jupiter + 5.11.0 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 25 + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + + + diff --git a/streams/scripts/run-all.sh b/streams/scripts/run-all.sh new file mode 100755 index 0000000..a786394 --- /dev/null +++ b/streams/scripts/run-all.sh @@ -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." diff --git a/streams/scripts/run.sh b/streams/scripts/run.sh new file mode 100755 index 0000000..e2ad42b --- /dev/null +++ b/streams/scripts/run.sh @@ -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" diff --git a/streams/src/main/java/com/ankurm/streams/CollectorsCookbookDemo.java b/streams/src/main/java/com/ankurm/streams/CollectorsCookbookDemo.java new file mode 100644 index 0000000..7f276b8 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/CollectorsCookbookDemo.java @@ -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 orders = Order.sample(); + + System.out.println("== groupingBy and downstream collectors =="); + Map> 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> 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))); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/CreationDemo.java b/streams/src/main/java/com/ankurm/streams/CreationDemo.java new file mode 100644 index 0000000..3ee64d3 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/CreationDemo.java @@ -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 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()); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/GatherersDemo.java b/streams/src/main/java/com/ankurm/streams/GatherersDemo.java new file mode 100644 index 0000000..44a5586 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/GatherersDemo.java @@ -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 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 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 lastSeen = () -> new int[] {Integer.MIN_VALUE}; + Gatherer 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]"); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/IntermediateOpsDemo.java b/streams/src/main/java/com/ankurm/streams/IntermediateOpsDemo.java new file mode 100644 index 0000000..0562580 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/IntermediateOpsDemo.java @@ -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 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 words = List.of("hello", "world", "java"); + System.out.println("map toUpperCase : " + words.stream().map(String::toUpperCase).toList()); + + List> 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) + .mapMulti((n, sink) -> { sink.accept(n); if (n % 2 == 0) sink.accept(n); }).toList()); + + List 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 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 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"); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/LazyPipelineDemo.java b/streams/src/main/java/com/ankurm/streams/LazyPipelineDemo.java new file mode 100644 index 0000000..b3a7172 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/LazyPipelineDemo.java @@ -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 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 s = Stream.of("a", "b"); + s.toList(); + try { + s.toList(); + } catch (IllegalStateException e) { + System.out.println("IllegalStateException: " + e.getMessage()); + } + } +} diff --git a/streams/src/main/java/com/ankurm/streams/LoopToStreamDemo.java b/streams/src/main/java/com/ankurm/streams/LoopToStreamDemo.java new file mode 100644 index 0000000..9b68c6d --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/LoopToStreamDemo.java @@ -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 orders = Order.sample(); + + System.out.println("== 1. The straightforward conversion =="); + Map loopRevenue = new TreeMap<>(); + for (Order o : orders) { + if (o.amount() >= 500) { + loopRevenue.merge(o.country(), o.amount(), Double::sum); + } + } + Map 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 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 loopNames = new ArrayList<>(); + for (Order o : orders) { + loopNames.add(o.customer()); + } + loopNames.add("extra"); + System.out.println("loop list after add : " + loopNames); + List 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)"); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/Order.java b/streams/src/main/java/com/ankurm/streams/Order.java new file mode 100644 index 0000000..25b22b7 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/Order.java @@ -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 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")); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/ParallelDemo.java b/streams/src/main/java/com/ankurm/streams/ParallelDemo.java new file mode 100644 index 0000000..450585d --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/ParallelDemo.java @@ -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 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 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 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()); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/PrimitiveStreamsDemo.java b/streams/src/main/java/com/ankurm/streams/PrimitiveStreamsDemo.java new file mode 100644 index 0000000..dba6d32 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/PrimitiveStreamsDemo.java @@ -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 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.reduce sum : " + Stream.of(Integer.MAX_VALUE, 1).reduce(0, Integer::sum) + " <- also wraps"); + } +} diff --git a/streams/src/main/java/com/ankurm/streams/TerminalOpsDemo.java b/streams/src/main/java/com/ankurm/streams/TerminalOpsDemo.java new file mode 100644 index 0000000..bcaeb16 --- /dev/null +++ b/streams/src/main/java/com/ankurm/streams/TerminalOpsDemo.java @@ -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 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.empty().reduce(Integer::sum)); + System.out.println("reduce(\"\", join) : " + Stream.of("Java", "Streams", "are", "powerful") + .reduce("", (a, b) -> a.isEmpty() ? b : a + " " + b)); + + List 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.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 unmodifiable = Stream.of(1, 2, 3).toList(); + List 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"; + } + } +} diff --git a/streams/src/test/java/com/ankurm/streams/StreamsContractTest.java b/streams/src/test/java/com/ankurm/streams/StreamsContractTest.java new file mode 100644 index 0000000..b068981 --- /dev/null +++ b/streams/src/test/java/com/ankurm/streams/StreamsContractTest.java @@ -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 s = Stream.of(1, 2, 3).peek(n -> calls.incrementAndGet()); + assertEquals(0, calls.get()); + s.toList(); + assertEquals(3, calls.get()); + } + + @Test + void streamIsSingleUse() { + Stream 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 p = Order.sample().stream().collect(partitioningBy(o -> o.amount() > 5000, counting())); + Map 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 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 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()); + } +}