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
+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