Working with Stream API

1. Creating Streams

SourceMethod
Collectioncoll.stream() / parallelStream()
ArrayArrays.stream(arr) / Stream.of(arr)
ValuesStream.of(a, b, c)
EmptyStream.empty()
InfiniteStream.iterate(seed, fn), Stream.generate(supplier)
RangeIntStream.range(0, n)
File linesFiles.lines(path)
BuilderStream.<T>builder().add(...).build()

2. Using Intermediate Operations

OperationDescription
filter(p)Keep matching
map(fn)Transform each
flatMap(fn)Map to stream, then flatten
distinct()Remove duplicates
sorted() / sorted(cmp)Sort elements
limit(n) / skip(n)Truncate
peek(c)Side-effect (debug)
Note: Intermediate ops are LAZY — nothing happens until terminal op runs.

3. Using Terminal Operations

OpReturns
forEach(c)void
toList() / toArray()Collection
collect(collector)Custom result
reduce(...)Accumulated value
count()long
min/maxOptional
findFirst/findAnyOptional
anyMatch/allMatch/noneMatchboolean

4. Filtering Elements

Example: Filter

List<User> active = users.stream()
    .filter(User::isActive)
    .filter(u -> u.age() >= 18)
    .toList();
MethodDetail
filter(predicate)Keep elements where predicate is true
CombineMultiple filters chain naturally

5. Mapping Elements

MethodUse
map(fn)1-to-1 transform
mapToInt/Long/DoubleSpecialized streams (no boxing)
mapToObjFrom primitive back to object stream

6. Flattening Streams

Example: flatMap

List<Order> orders = ...;
List<Item> allItems = orders.stream()
    .flatMap(o -> o.items().stream())
    .toList();
MethodUse
flatMap(fn)1-to-many → flat
mapMulti(biCons) JAVA 16+Push-style flatMap (more efficient for few-to-one)

7. Sorting Streams

FormDetail
sorted()Natural order (Comparable required)
sorted(cmp)Custom comparator
Stateful opBuffers all elements

8. Removing Duplicates

OpDetail
distinct()By equals/hashCode
Custom keyUse collectingAndThen(toMap(keyFn, identity(), (a,b)->a), m -> m.values().stream())

9. Limiting Streams

OpDetail
limit(n)First n elements (short-circuiting)
skip(n)Skip first n
takeWhile(p) JAVA 9+Take while predicate true
dropWhile(p) JAVA 9+Drop while predicate true

10. Peeking Elements

AspectDetail
UseDebug logging mid-pipeline
CautionDon't mutate state in peek

11. Checking Conditions

MethodBehavior
anyMatch(p)Short-circuit on first match
allMatch(p)Short-circuit on first non-match
noneMatch(p)Short-circuit on first match
Empty streamallMatch=true, anyMatch=false, noneMatch=true

12. Finding Elements

MethodBehavior
findFirst()First per encounter order
findAny()Any element (better for parallel)
ReturnsOptional<T>

13. Understanding Parallel Streams

AspectDetail
Activatecoll.parallelStream() or stream.parallel()
BackingCommon ForkJoinPool
Best forLarge data + CPU-bound + stateless ops
AvoidI/O, shared mutable state, ordered ops
Warning: Parallel streams use a shared pool — slow tasks can starve other parallel work.