A Stream is a sequence of elements you process using a pipeline of operations, instead of writing manual loops. Intermediate operations are lazy — nothing runs until a terminal operation triggers the whole pipeline, element by element.
(params) -> expression or (params) -> { statements; }map() transforms each element into something newreduce() — combines all elements into one resultcount(), sum(), average()collect(Collectors.toList()) — gather into a collection::)Predicate<T>test(T t) → boolean
used by filter()
Function<T,R>apply(T t) → R
used by map()
Consumer<T>accept(T t) → void
used by forEach()
Supplier<T>get() → T
produces a value, no input
An infinite stream (Stream.iterate, Stream.generate) has no natural end — always pair it with limit(n) or it will never terminate.
| Intermediate (lazy) | Purpose |
|---|---|
filter(predicate) | keeps elements matching a condition |
map(function) | transforms each element |
sorted() | sorts elements |
distinct() | removes duplicates |
limit(n) | keeps only the first n |
skip(n) | skips the first n |
| Terminal (triggers execution) | Purpose |
|---|---|
forEach(consumer) | performs an action on each element |
collect(collector) | gathers results into a List/Set/Map |
reduce(identity, op) | combines all elements into one value |
count() | number of elements |
anyMatch/allMatch/noneMatch(p) | boolean tests across elements |
findFirst() | an Optional with the first element |