Java Streams
Stream pipeline: source, intermediate operations, terminal operations, lazy evaluation, and parallel streams
- Build complex data pipelines with filter, map, flatMap, reduce, collect
- Understand lazy evaluation and short-circuit operations
- Use Collectors for groupingBy, partitioning, joining, and custom reductions
- Decide when to use parallel streams safely
A professional-quality reference covering everything from basics to internals, with code examples, diagrams, and interview preparation.
Table of Contents
- What is a Stream?
- The Three-Step Pipeline
- Ways to Create a Stream
- Intermediate Operations
- Lazy Evaluation — Why Streams Are "Lazy"
- Stream Execution Order — The Surprising Truth
- Terminal Operations
- Stream Reuse and Closing
- Parallel Streams
- Key Differences — Sequential vs Parallel Streams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary — Quick Revision Bullets
1. What is a Stream?
Overview
A Stream in Java is a sequence of elements that supports sequential and parallel operations. Think of it as a pipeline — data enters at one end, passes through a series of processing stages, and exits as a result at the other end.
Streams are part of the java.util.stream package, introduced in Java 8.
Real-World Analogy
Imagine a water treatment pipeline:
1[Water Source] → [Filter Stage] → [Purification Stage] → [Output Tap]- The water source = your collection (List, Array, etc.)
- The filter and purification stages = intermediate operations (filter, map, sort, etc.)
- The output tap = terminal operation (collect, count, forEach, etc.)
- The water flowing through = data elements
Water passes through each stage in sequence. The original reservoir (source) is never changed — you only draw from it.
Definition
A Stream is a pipeline through which data elements pass. It supports a sequence of operations — zero or more intermediate operations that transform the stream, followed by exactly one terminal operation that produces a result or a side-effect.
Why Streams Exist
Before Java 8, processing a collection required verbose for loops and conditional blocks. Streams solve this by providing:
| Problem (Before Streams) | Solution (With Streams) |
|---|---|
Verbose for loops for filtering | stream().filter(...) |
| Manual counting of elements | .count() |
| Manual sorting and collecting | .sorted().collect(...) |
| No built-in parallel processing | .parallelStream() |
| Code that mixes what and how | Streams separate what from how |
Key Properties of Streams
| Property | Description |
|---|---|
| Not a data structure | Doesn't store elements; operates on a source |
| Functional in nature | Operations produce results without modifying the source |
| Lazy | Intermediate operations execute only when a terminal operation is invoked |
| Possibly infinite | Can represent an infinite sequence (e.g., Stream.iterate) |
| Consumable | A stream can only be traversed once; it is closed after the terminal operation |
| Can be sequential or parallel | Use .stream() or .parallelStream() |
Internal Working
Internally, a Stream is backed by:
- A source (collection, array, generator, etc.)
- A chain of intermediate operation descriptors — these are stored lazily (not executed yet)
- A terminal operation that, when invoked, triggers the pipeline
The JVM uses a Spliterator internally to traverse and optionally split the source for parallel processing.
2. The Three-Step Pipeline
Every Stream operation follows exactly this structure:
1[Step 1: Open / Create a Stream]2 ↓3[Step 2: Zero or More Intermediate Operations]4 ↓5[Step 3: Exactly One Terminal Operation]Step 1 Create a Stream
You must first open or create a stream from your data source. This does not process data — it only sets up the pipeline.
1List<Integer> salaries = Arrays.asList(3000, 4000, 10000, 9000, 1000, 3500);2Stream<Integer> stream = salaries.stream(); // Step 1: open a streamStep 2 Intermediate Operations (Zero or More)
Intermediate operations transform the stream from one form into another stream. They are:
- Lazy — they don't execute until a terminal operation is called
- Chainable — you can chain many of them together
- Non-destructive — the source data is never modified
1stream.filter(salary -> salary > 3000) // intermediate operation 12 .sorted() // intermediate operation 2Step 3 Terminal Operation (Exactly One)
The terminal operation:
- Triggers the execution of the entire stream pipeline
- Produces a result (a value, a collection,
void, etc.) - Closes the stream — no more operations can be added after this
1long count = stream.filter(salary -> salary > 3000)2 .count(); // terminal operation — triggers pipeline, closes streamCode Example With and Without Stream
Without Stream (Traditional Loop)
1import java.util.Arrays;2import java.util.List;3
4public class WithoutStream {5 public static void main(String[] args) {6 List<Integer> salaries = Arrays.asList(3000, 4000, 10000, 9000, 1000, 3500);7
8 int count = 0;9 for (int salary : salaries) {10 if (salary > 3000) {11 count++;12 }13 }14
15 System.out.println("Total employees with salary greater than 3000 is: " + count);16 }17}Total employees with salary greater than 3000 is: 3
Explanation:
- We iterate over each salary manually using a
for-eachloop. - If the salary exceeds 3000, we increment a counter.
- Final count = 3 (salaries: 4000, 10000, 9000 qualify).
With Stream
1import java.util.Arrays;2import java.util.List;3
4public class WithStream {5 public static void main(String[] args) {6 List<Integer> salaries = Arrays.asList(3000, 4000, 10000, 9000, 1000, 3500);7
8 long count = salaries.stream() // Step 1: create stream9 .filter(s -> s > 3000) // Step 2: intermediate operation10 .count(); // Step 3: terminal operation11
12 System.out.println("Total employees with salary greater than 3000 is: " + count);13 }14}Total employees with salary greater than 3000 is: 3
Line-by-Line Explanation:
| Line | What Happens |
|---|---|
salaries.stream() | Creates a Stream from the list. No data is processed yet. |
.filter(s -> s > 3000) | Registers a filter that will keep only elements > 3000. Still not executed. |
.count() | This is the terminal operation. It triggers the pipeline: filter runs, and the count of remaining elements is returned. Stream is closed. |
3. Ways to Create a Stream
There are multiple ways to create a stream in Java, depending on your data source.
3.1 From a Collection (List, Set, etc.)
The most common approach. Every Collection exposes a .stream() method.
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Stream;4
5List<Integer> salaries = new ArrayList<>(Arrays.asList(3000, 4000, 10000));6Stream<Integer> stream = salaries.stream();salaries.stream()creates a sequentialStream.- Works for any class that implements
Collection(List, Set, Queue, etc.).
3.2 From an Array
Use Arrays.stream() to create a stream from an array.
1import java.util.Arrays;2import java.util.stream.Stream;3
4Integer[] arr = {3000, 4000, 10000};5Stream<Integer> stream = Arrays.stream(arr);For primitive arrays, you get a specialized stream:
1int[] primitiveArr = {3000, 4000, 10000};2IntStream intStream = Arrays.stream(primitiveArr); // returns IntStream, not Stream<Integer>Arrays.stream() with a primitive array returns IntStream, LongStream, or DoubleStream — not Stream. These are specialized for performance (no boxing/unboxing overhead).3.3 From Static Method `Stream.of()`
Use Stream.of() to create a stream directly from values (varargs).
1import java.util.stream.Stream;2
3Stream<Integer> stream = Stream.of(3000, 4000, 10000);- Accepts variable arguments (varargs).
- Useful for small, inline datasets.
3.4 From Stream Builder
Use Stream.builder() to add elements programmatically before building the stream.
1import java.util.stream.Stream;2
3Stream.Builder<String> builder = Stream.builder();4builder.add("Java");5builder.add("Streams");6builder.add("Are Fun");7Stream<String> stream = builder.build();Step-by-Step:
Stream.builder()returns aStream.Builderobject..add(element)adds elements to the builder..build()constructs and returns the final stream.
3.5 From `Stream.iterate()` Infinite Streams
Stream.iterate() creates a potentially infinite stream by repeatedly applying a function.
1import java.util.stream.Stream;2
3Stream<Integer> stream = Stream.iterate(1000, n -> n + 5000)4 .limit(5); // MUST limit, or it runs forever!What this produces: 1000, 6000, 11000, 16000, 21000
| Parameter | Meaning |
|---|---|
1000 | Seed — the starting value |
n -> n + 5000 | UnaryOperator — how each next value is derived from the previous |
.limit(5) | Stops after 5 elements — mandatory for infinite streams |
Stream.iterate() with .limit() or another limiting terminal operation. Without it, the stream will run indefinitely and cause an out-of-memory error or infinite loop.Summary Table Ways to Create Streams
| Method | Source | Return Type | Notes |
|---|---|---|---|
collection.stream() | Any Collection | Stream | Most common |
Arrays.stream(array) | Array | Stream or IntStream etc. | Works for both object and primitive arrays |
Stream.of(values...) | Inline values | Stream | Varargs |
Stream.builder() | Programmatic | Stream | Add elements then .build() |
Stream.iterate(seed, fn) | Computed | Stream | Infinite; use with .limit() |
4. Intermediate Operations
Intermediate operations are operations that:
- Accept a stream as input
- Return a new stream as output (transformed)
- Are lazy — not executed until a terminal operation is invoked
- Can be chained together
Stream. They never return a final result like a number, list, or boolean.4.1 `filter(Predicate<T>)`
Purpose: Keeps only elements that satisfy a given condition. Removes elements for which the predicate returns false.
Functional Interface Used: Predicate — has one abstract method boolean test(T t)
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class FilterExample {6 public static void main(String[] args) {7 List<String> words = Arrays.asList("Hello", "everybody", "How", "are", "you", "doing");8
9 List<String> shortWords = words.stream()10 .filter(name -> name.length() <= 3) // keep words with length ≤ 311 .collect(Collectors.toList());12
13 System.out.println(shortWords);14 }15}[How, are, you]
Step-by-Step Execution:
- Stream created from
wordslist. filteriterates over each word, calls the predicate."Hello"→ length 5 →false→ excluded"everybody"→ length 9 →false→ excluded"How"→ length 3 →true→ included"are"→ length 3 →true→ included"you"→ length 3 →true→ included"doing"→ length 5 →false→ excludedcollectgathers the remaining stream elements into a List.
4.2 `map(Function<T, R>)`
Purpose: Transforms each element in the stream into a new form. The input and output types can differ.
Functional Interface Used: Function — has one abstract method R apply(T t) — accepts one value, returns one value.
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class MapExample {6 public static void main(String[] args) {7 List<String> words = Arrays.asList("Hello", "EVERYBODY", "HOW", "ARE", "YOU", "DOING");8
9 List<String> lowerCaseWords = words.stream()10 .map(name -> name.toLowerCase()) // transform each element11 .collect(Collectors.toList());12
13 System.out.println(lowerCaseWords);14 }15}[hello, everybody, how, are, you, doing]
What Happens Internally:
mapiterates over each element and passes it to theFunctioninterface.- The function receives
"Hello", returns"hello". - The output is placed into a new stream.
- The original list is not modified.
map does a one-to-one transformation: for each input element, exactly one output element is produced.4.3 `flatMap(Function<T, Stream<R>>)`
Purpose: Used when each element of the stream is itself a collection or stream. flatMap flattens these nested collections into a single stream.
Key Difference from map:
map:Stream→ still- >
Stream- >
flatMap:Stream→- >
Stream(flattened)
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class FlatMapExample {6 public static void main(String[] args) {7 List<List<String>> sentences = Arrays.asList(8 Arrays.asList("I", "love", "Java"),9 Arrays.asList("concepts", "are", "clear"),10 Arrays.asList("it's", "very", "easy")11 );12
13 // Without flatMap, stream gives Stream<List<String>>14 // With flatMap, we get Stream<String>15 List<String> allWords = sentences.stream()16 .flatMap(sentence -> sentence.stream()) // flatten each list into its stream17 .collect(Collectors.toList());18
19 System.out.println(allWords);20 }21}[I, love, Java, concepts, are, clear, it's, very, easy]
Advanced FlatMap — with transformation inside:
1List<String> allWordsLower = sentences.stream()2 .flatMap(sentence -> sentence.stream()3 .map(String::toLowerCase)) // lowercase inside flatMap4 .collect(Collectors.toList());5
6System.out.println(allWordsLower);[i, love, java, concepts, are, clear, it's, very, easy]
4.4 `distinct()`
Purpose: Removes duplicate elements from the stream. Uses equals() for comparison.
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class DistinctExample {6 public static void main(String[] args) {7 Integer[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};8 List<Integer> unique = Arrays.stream(arr)9 .distinct()10 .collect(Collectors.toList());11
12 System.out.println(unique);13 }14}[3, 1, 4, 5, 9, 2, 6]
distinct() uses equals() and hashCode() to identify duplicates. For custom objects, override these methods.4.5 `sorted()` and `sorted(Comparator)`
Purpose: Sorts the elements of the stream.
sorted()— natural order (ascending for numbers, alphabetical for strings)sorted(Comparator)— custom order
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class SortedExample {6 public static void main(String[] args) {7 Integer[] arr = {10, 2, 4, 7, 1, 2, 4, 5};8
9 // Natural (ascending) order10 List<Integer> ascending = Arrays.stream(arr)11 .distinct()12 .sorted()13 .collect(Collectors.toList());14 System.out.println("Ascending: " + ascending);15
16 // Descending order using Comparator17 List<Integer> descending = Arrays.stream(arr)18 .distinct()19 .sorted((a, b) -> b - a) // b - a = descending20 .collect(Collectors.toList());21 System.out.println("Descending: " + descending);22 }23}Ascending: [1, 2, 4, 5, 7, 10] Descending: [10, 7, 5, 4, 2, 1]
sorted() is a stateful intermediate operation — it must see all elements before it can produce any output. This affects stream execution order (covered in Section 6).4.6 `peek(Consumer<T>)`
Purpose: Performs an action on each element as it passes through, without modifying the stream. Mainly used for debugging.
Functional Interface Used: Consumer — accepts one value, returns nothing (void).
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class PeekExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 6);8
9 List<Integer> result = numbers.stream()10 .filter(v -> v > 2)11 .peek(v -> System.out.println("After filter: " + v)) // debug peek12 .collect(Collectors.toList());13
14 System.out.println("Result: " + result);15 }16}After filter: 3 After filter: 4 After filter: 6 Result: [3, 4, 6]
peek to inspect stream elements at any point in the pipeline during debugging. Remove it in production code.4.7 `limit(long maxSize)`
Purpose: Truncates the stream to contain no more than maxSize elements.
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class LimitExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(2, 1, 3, 4, 5, 6);8
9 List<Integer> limited = numbers.stream()10 .limit(3)11 .collect(Collectors.toList());12
13 System.out.println(limited);14 }15}[2, 1, 3]
limit() is a short-circuiting intermediate operation — it can stop processing the stream early, which is a performance benefit for large or infinite streams.4.8 `skip(long n)`
Purpose: Skips the first n elements of the stream.
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4
5public class SkipExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 6);8
9 List<Integer> skipped = numbers.stream()10 .skip(3) // skip first 3 elements11 .collect(Collectors.toList());12
13 System.out.println(skipped);14 }15}[4, 6]
4.9 `mapToInt()`, `mapToLong()`, `mapToDouble()`
Purpose: Converts a Stream to a specialized primitive stream (IntStream, LongStream, DoubleStream). This avoids boxing/unboxing overhead when working with primitive types.
Why this exists:
Streamuses boxedIntegerobjects (heap allocation, boxing overhead)IntStreamuses primitiveintvalues (stack, no boxing, faster)
1import java.util.Arrays;2import java.util.List;3import java.util.stream.IntStream;4
5public class MapToIntExample {6 public static void main(String[] args) {7 // Converting String list to int values8 List<String> strNumbers = Arrays.asList("2", "1", "4", "7");9
10 int[] intArr = strNumbers.stream()11 .mapToInt(s -> Integer.parseInt(s)) // convert String -> int12 .toArray();13
14 System.out.println(Arrays.toString(intArr));15 }16}[2, 1, 4, 7]
Working with primitive int array directly:
1int[] primitiveArr = {3000, 4000, 10000};2IntStream intStream = Arrays.stream(primitiveArr);3// Now you can do intStream.filter(...).sum() etc. on primitive intsIntStream, LongStream, and DoubleStream are specialized versions of Stream for primitive types. They have additional terminal operations like .sum(), .average(), .min(), .max() that aren't available on Stream.Summary Table Intermediate Operations
| Operation | Input | Output | Functional Interface | Purpose |
|---|---|---|---|---|
filter(predicate) | Stream | Stream | Predicate | Keep elements matching condition |
map(function) | Stream | Stream | Function | Transform each element |
flatMap(function) | Stream | Stream | Function | Flatten nested collections |
distinct() | Stream | Stream | — | Remove duplicates |
sorted() | Stream | Stream | — | Sort in natural order |
sorted(comparator) | Stream | Stream | Comparator | Sort with custom order |
peek(consumer) | Stream | Stream | Consumer | Side-effect / debug |
limit(n) | Stream | Stream | — | Truncate to n elements |
skip(n) | Stream | Stream | — | Skip first n elements |
mapToInt(function) | Stream | IntStream | ToIntFunction | Convert to primitive int stream |
mapToLong(function) | Stream | LongStream | ToLongFunction | Convert to primitive long stream |
mapToDouble(function) | Stream | DoubleStream | ToDoubleFunction | Convert to primitive double stream |
5. Lazy Evaluation Why Streams Are "Lazy"
What Does "Lazy" Mean?
Intermediate operations are lazy. This means:
Intermediate operations do not execute when they are declared. They are only executed when a terminal operation is invoked.
This is one of the most important and frequently misunderstood properties of Java Streams.
Demonstration Lazy Evaluation
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Stream;4
5public class LazyExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(2, 1, 4, 7, 10);8
9 // Step 1: create stream10 // Step 2: add intermediate operations11 Stream<Integer> filteredStream = numbers.stream()12 .filter(v -> v >= 3)13 .peek(v -> System.out.println("Peeking: " + v));14
15 // At this point — NOTHING has printed yet!16 System.out.println("Stream pipeline created but NOT yet executed.");17
18 // Step 3: Now invoke terminal operation19 long count = filteredStream.count();20
21 System.out.println("Count: " + count);22 }23}Stream pipeline created but NOT yet executed. Peeking: 4 Peeking: 7 Peeking: 10 Count: 3
Explanation:
- After
.filter()and.peek()are declared — nothing runs. The filter does not filter. The peek does not print. - The line
"Stream pipeline created but NOT yet executed."prints first. - Only when
.count()is called does the pipeline begin executing. The filter runs, the peek runs, and the count is computed.
Why Is Lazy Evaluation Beneficial?
Consider this: you have a list of 1 million employees and you want to find any one whose salary exceeds 3000.
1Optional<Integer> found = salaries.stream()2 .filter(s -> s > 3000)3 .findFirst(); // terminal operationThanks to lazy evaluation:
- Stream processes elements one at a time.
- As soon as the first match is found, the pipeline stops immediately.
- It does not process all 1 million elements unnecessarily.
Without lazy evaluation, filter would first process all 1 million elements, and then findFirst would take the first — very inefficient!
6. Stream Execution Order The Surprising Truth
What Most People Expect
When looking at a stream like:
1list.stream()2 .filter(...) // pass all elements through filter first3 .peek(...) // then peek all elements4 .map(...) // then map all elements5 .sorted() // then sort all elements6 .peek(...) // then peek all elements again7 .forEach(...) // then print allMost people expect the stream to:
- Run all elements through
filter, producing a filtered list - Then run all of those through
peek - Then through
map, etc.
This is NOT how Java streams work.
What Actually Happens
Java streams process elements one at a time, passing each element as far down the pipeline as possible before picking up the next element — except for stateful operations like sorted() that need all elements before they can proceed.
Full Demonstration
1import java.util.Arrays;2import java.util.List;3
4public class ExecutionOrderExample {5 public static void main(String[] args) {6 List<Integer> numbers = Arrays.asList(2, 1, 4, 7, 10);7
8 numbers.stream()9 .filter(v -> {10 System.out.println("Filter: " + v);11 return v >= 4;12 })13 .peek(v -> System.out.println("After filter peek: " + v))14 .map(v -> {15 int negated = -v;16 System.out.println("Map: " + v + " → " + negated);17 return negated;18 })19 .peek(v -> System.out.println("After map peek: " + v))20 .sorted()21 .peek(v -> System.out.println("After sorted peek: " + v))22 .forEach(v -> System.out.println("Final: " + v));23 }24}Filter: 2 Filter: 1 Filter: 4 After filter peek: 4 Map: 4 → -4 After map peek: -4 Filter: 7 After filter peek: 7 Map: 7 → -7 After map peek: -7 Filter: 10 After filter peek: 10 Map: 10 → -10 After map peek: -10 After sorted peek: -10 After sorted peek: -7 After sorted peek: -4 Final: -10 Final: -7 Final: -4
Why This Output?
Key Insight:
| Operation Type | Behavior |
|---|---|
| Stateless (filter, map, peek, limit) | Processes elements one at a time, passes each element to the next operation immediately |
| Stateful (sorted, distinct) | Must wait for ALL elements before it can produce output |
This element-by-element processing gives streams an important performance advantage: for operations like findFirst() or anyMatch(), the stream can short-circuit — stop early as soon as the answer is found.
7. Terminal Operations
Terminal operations:
- Trigger execution of the entire stream pipeline (because streams are lazy)
- Produce a result or side-effect
- Close the stream — no further operations can be added or run
7.1 `forEach(Consumer<T>)`
Purpose: Performs an action for each element. Does not return a value.
1import java.util.Arrays;2import java.util.List;3
4public class ForEachExample {5 public static void main(String[] args) {6 List<Integer> numbers = Arrays.asList(1, 4, 7, 10);7
8 numbers.stream()9 .filter(v -> v >= 4)10 .forEach(v -> System.out.println(v));11 }12}4 7 10
7.2 `toArray()`
Purpose: Collects stream elements into an array.
1import java.util.Arrays;2import java.util.List;3
4public class ToArrayExample {5 public static void main(String[] args) {6 List<String> names = Arrays.asList("Alice", "Bob", "Charlie");7
8 // Returns Object[]9 Object[] objectArr = names.stream().toArray();10
11 // Returns String[] using generator12 String[] stringArr = names.stream().toArray(String[]::new);13
14 System.out.println(Arrays.toString(stringArr));15 }16}[Alice, Bob, Charlie]
Explanation of String[]::new:
- This is a constructor reference — it tells
toArrayto create aString[]of the required size. - Equivalent to:
size -> new String[size]
7.3 `reduce(BinaryOperator<T>)`
Purpose: Performs a reduction on the elements using an associative accumulation function, and returns an Optional.
"Associative Aggregation Function" means:
- Take two elements at a time
- Combine them into one
- Repeat until only one value remains
1import java.util.Arrays;2import java.util.List;3import java.util.Optional;4
5public class ReduceExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(1, 4, 7, 10);8
9 // Sum using reduce10 Optional<Integer> sum = numbers.stream()11 .reduce((v1, v2) -> v1 + v2);12
13 System.out.println("Sum: " + sum.get());14
15 // Product using reduce16 Optional<Integer> product = numbers.stream()17 .reduce((v1, v2) -> v1 * v2);18
19 System.out.println("Product: " + product.get());20 }21}Sum: 22 Product: 280
Step-by-Step for Sum:
1Step 1: v1=1, v2=4 → result=52Step 2: v1=5, v2=7 → result=123Step 3: v1=12, v2=10 → result=224Final: 22What is Optional?
Optional is a container that may or may not contain a non-null value. It prevents NullPointerException:
1Optional<Integer> result = stream.reduce(...);2if (!result.isEmpty()) {3 System.out.println(result.get()); // safely get the value4}reduce() returns Optional because if the stream is empty, there is no value to return. Optional lets you check this safely instead of getting a NullPointerException.7.4 `collect(Collector)`
Purpose: The most versatile terminal operation. Collects stream elements into a mutable result container (like a List, Set, Map, etc.).
1import java.util.Arrays;2import java.util.List;3import java.util.Set;4import java.util.stream.Collectors;5
6public class CollectExample {7 public static void main(String[] args) {8 List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);9
10 // Collect to List11 List<Integer> list = numbers.stream()12 .filter(n -> n > 3)13 .collect(Collectors.toList());14 System.out.println("List: " + list);15
16 // Collect to Set (removes duplicates automatically)17 Set<Integer> set = numbers.stream()18 .collect(Collectors.toSet());19 System.out.println("Set: " + set);20 }21}List: [4, 5, 9, 6] Set: [1, 2, 3, 4, 5, 6, 9]
7.5 `min(Comparator)` and `max(Comparator)`
Purpose: Find the minimum or maximum element based on a comparator.
1import java.util.Arrays;2import java.util.List;3import java.util.Optional;4
5public class MinMaxExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(4, 7, 10, 3);8
9 // Minimum in natural (ascending) order10 Optional<Integer> min = numbers.stream()11 .filter(n -> n >= 3)12 .min((v1, v2) -> v1 - v2); // v1 - v2 = ascending order13 System.out.println("Min: " + min.get());14
15 // Maximum in natural order16 Optional<Integer> max = numbers.stream()17 .max((v1, v2) -> v1 - v2);18 System.out.println("Max: " + max.get());19 }20}Min: 3 Max: 10
Comparator.naturalOrder() and Comparator.reverseOrder() for clarity:
``java
.min(Comparator.naturalOrder())
.max(Comparator.naturalOrder())
``7.6 `count()`
Purpose: Returns the number of elements in the stream as a long.
1List<Integer> numbers = Arrays.asList(1, 4, 7, 10);2
3long count = numbers.stream()4 .filter(n -> n >= 4)5 .count();6
7System.out.println("Count: " + count); // Output: 37.7 `anyMatch(Predicate)`, `allMatch(Predicate)`, `noneMatch(Predicate)`
Purpose: Test whether elements match a condition. Return a boolean.
| Method | Returns true when... |
|---|---|
anyMatch(p) | At least one element matches p |
allMatch(p) | All elements match p |
noneMatch(p) | No element matches p |
1import java.util.Arrays;2import java.util.List;3
4public class MatchExample {5 public static void main(String[] args) {6 List<Integer> numbers = Arrays.asList(2, 1, 4, 7);7
8 boolean any = numbers.stream().anyMatch(n -> n > 3); // true (4 and 7 qualify)9 boolean all = numbers.stream().allMatch(n -> n > 0); // true (all are positive)10 boolean none = numbers.stream().noneMatch(n -> n > 10); // true (none exceed 10)11
12 System.out.println("anyMatch > 3: " + any);13 System.out.println("allMatch > 0: " + all);14 System.out.println("noneMatch > 10: " + none);15 }16}anyMatch > 3: true allMatch > 0: true noneMatch > 10: true
anyMatch stops at the first true; allMatch stops at the first false.7.8 `findFirst()` and `findAny()`
Purpose: Return an Optional with an element from the stream.
| Method | Returns |
|---|---|
findFirst() | The first element of the stream (respects encounter order) |
findAny() | Any element (no order guarantee; useful in parallel streams) |
1import java.util.Arrays;2import java.util.List;3import java.util.Optional;4
5public class FindExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(4, 7, 10);8
9 Optional<Integer> first = numbers.stream()10 .filter(n -> n >= 4)11 .findFirst();12 System.out.println("First: " + first.get()); // 413
14 Optional<Integer> any = numbers.stream()15 .filter(n -> n >= 4)16 .findAny();17 System.out.println("Any: " + any.get()); // 4, 7, or 10 — random18 }19}First: 4 Any: 4
findAny() can return any element from any thread and is faster. findFirst() guarantees the first element but may be slower in parallel because threads must coordinate.Summary Table Terminal Operations
| Operation | Return Type | Purpose |
|---|---|---|
forEach(consumer) | void | Perform action on each element |
toArray() | Object[] or T[] | Collect into array |
reduce(binaryOp) | Optional | Aggregate into single value |
collect(collector) | R (List, Set, Map, etc.) | Collect into container |
min(comparator) | Optional | Find minimum element |
max(comparator) | Optional | Find maximum element |
count() | long | Count elements |
anyMatch(predicate) | boolean | Any element matches? |
allMatch(predicate) | boolean | All elements match? |
noneMatch(predicate) | boolean | No element matches? |
findFirst() | Optional | First element |
findAny() | Optional | Any element (useful in parallel) |
8. Stream Reuse and Closing
A Stream Can Only Be Used Once
Once a terminal operation is invoked, the stream is closed. Attempting to reuse it throws an exception.
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Stream;4
5public class StreamReuseExample {6 public static void main(String[] args) {7 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);8
9 Stream<Integer> stream = numbers.stream()10 .filter(n -> n > 2);11
12 // First use — OK13 stream.forEach(System.out::println);14
15 // Second use — THROWS EXCEPTION16 stream.collect(java.util.stream.Collectors.toList()); // ❌ IllegalStateException17 }18}Exception:
1java.lang.IllegalStateException: stream has already been operated upon or closedHow to fix:
Create a new stream each time you need to process the data:
1// First use2numbers.stream().filter(n -> n > 2).forEach(System.out::println);3
4// Second use — create a NEW stream5List<Integer> result = numbers.stream().filter(n -> n > 2).collect(Collectors.toList());.stream() again.9. Parallel Streams
Overview
A parallel stream divides the data into multiple chunks and processes them concurrently using multiple CPU cores. This can dramatically reduce processing time for large datasets.
- Sequential stream:
.stream() - Parallel stream:
.parallelStream()
The only code change needed is .parallelStream() instead of .stream().
Code Example Sequential vs Parallel
1import java.util.Arrays;2import java.util.List;3
4public class ParallelStreamExample {5 public static void main(String[] args) {6 List<Integer> numbers = Arrays.asList(7 11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 1218 );9
10 // Sequential11 long seqStart = System.currentTimeMillis();12 numbers.stream()13 .map(n -> n * n)14 .forEach(n -> System.out.print(n + " "));15 long seqTime = System.currentTimeMillis() - seqStart;16 System.out.println("\nSequential time: " + seqTime + " ms");17
18 // Parallel19 long parStart = System.currentTimeMillis();20 numbers.parallelStream()21 .map(n -> n * n)22 .forEach(n -> System.out.print(n + " "));23 long parTime = System.currentTimeMillis() - parStart;24 System.out.println("\nParallel time: " + parTime + " ms");25 }26}Approximate Output:
1121 484 1089 1936 3025 4356 5929 7744 9801 12100 14641 2Sequential time: 64 ms3
4484 121 3025 1936 1089 ... (order may vary)5Parallel time: 5 ms.forEachOrdered() instead of .forEach().How Parallel Streams Work Internally
Parallel streams use two key mechanisms:
1. Spliterator (Splittable Iterator)
When .parallelStream() is called, Java uses a Spliterator to divide the source data into chunks:
1// Called internally2SpliterableIterator<T> spliterator = collection.spliterator();The Spliterator has a method called trySplit():
- It finds the midpoint of the data
- Splits it into two halves
- Each half is itself a new
Spliterator - This continues recursively until chunks are small enough to process individually
1Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]2Split 1: [1,2,3,4,5] + [6,7,8,9,10]3Split 2: [1,2] [3,4,5] + [6,7] [8,9,10]4...and so on2. Fork/Join Pool
After splitting, the chunks are handed to the Fork/Join Pool:
- Fork = divide a task into smaller subtasks
- Join = combine results from completed subtasks
The Fork/Join pool maintains a pool of threads (usually equal to the number of CPU cores) and assigns chunks to available threads.
When to Use Parallel Streams
| Use Parallel Streams | Avoid Parallel Streams |
|---|---|
| Very large datasets (millions of elements) | Small collections (overhead not worth it) |
| CPU-intensive operations (sorting, complex math) | I/O-bound operations |
| Independent operations per element | Operations with shared mutable state |
| Order doesn't matter | Order-sensitive operations |
10. Key Differences Sequential vs Parallel Streams
| Feature | Sequential Stream | Parallel Stream |
|---|---|---|
| Creation | collection.stream() | collection.parallelStream() |
| Processing | Single thread, one element at a time | Multiple threads, concurrent chunks |
| Order | Encounter order preserved | Order not guaranteed (unless forEachOrdered) |
| Performance | Fast for small data | Faster for large CPU-intensive data |
| Overhead | None | Thread creation, coordination overhead |
| Internal mechanism | Simple iteration | Fork/Join Pool + Spliterator |
| Thread safety | Not a concern | Must ensure no shared mutable state |
11. Common Mistakes
Mistake 1: Forgetting the Terminal Operation
1// ❌ Wrong — no terminal operation, nothing happens2numbers.stream()3 .filter(n -> n > 3)4 .map(n -> n * 2);5// This produces a stream object but never executes it1// ✅ Correct2numbers.stream()3 .filter(n -> n > 3)4 .map(n -> n * 2)5 .collect(Collectors.toList()); // terminal operation triggers executionMistake 2: Reusing a Closed Stream
1Stream<Integer> stream = numbers.stream().filter(n -> n > 2);2stream.count(); // OK — stream now closed3stream.collect(Collectors.toList()); // ❌ IllegalStateException1// ✅ Create a new stream each time2numbers.stream().filter(n -> n > 2).count();3numbers.stream().filter(n -> n > 2).collect(Collectors.toList());Mistake 3: Using `Stream.iterate()` Without `.limit()`
1// ❌ Infinite stream — will run forever / crash2Stream.iterate(0, n -> n + 1).forEach(System.out::println);1// ✅ Always limit infinite streams2Stream.iterate(0, n -> n + 1).limit(10).forEach(System.out::println);Mistake 4: Assuming `peek()` is a Terminal Operation
1// ❌ Wrong — peek is intermediate; nothing runs without a terminal op2numbers.stream()3 .filter(n -> n > 2)4 .peek(System.out::println); // Nothing will print!1// ✅ Correct2numbers.stream()3 .filter(n -> n > 2)4 .peek(System.out::println)5 .count(); // terminal operation triggers everythingMistake 5: Modifying Source Inside a Stream
1List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));2
3// ❌ Modifying source during stream processing — undefined behavior / ConcurrentModificationException4numbers.stream().forEach(n -> {5 if (n > 3) numbers.remove(n); // DO NOT DO THIS6});1// ✅ Collect results and then remove2List<Integer> toRemove = numbers.stream()3 .filter(n -> n > 3)4 .collect(Collectors.toList());5numbers.removeAll(toRemove);Mistake 6: Using Parallel Streams with Shared Mutable State
1List<Integer> results = new ArrayList<>(); // shared mutable state2
3// ❌ Race condition — multiple threads modifying the same ArrayList4numbers.parallelStream().filter(n -> n > 3).forEach(results::add);1// ✅ Use collect() instead2List<Integer> results = numbers.parallelStream()3 .filter(n -> n > 3)4 .collect(Collectors.toList()); // thread-safe collection12. Best Practices
- Always end with a terminal operation. A stream pipeline without one is useless.
- Never reuse a stream. Create a new stream from the source each time.
- Keep lambdas simple and stateless. Avoid modifying external variables inside lambdas — especially in parallel streams.
- Use
peek()only for debugging, not for transforming data (that's whatmap()is for).
- Chain operations fluently for readability:
1 // ✅ Good — clearly reads as a pipeline2 list.stream()3 .filter(e -> e.getSalary() > 50000)4 .map(Employee::getName)5 .sorted()6 .collect(Collectors.toList());- Use method references when possible for clarity:
1 .map(String::toLowerCase) // instead of: .map(s -> s.toLowerCase())2 .forEach(System.out::println) // instead of: .forEach(s -> System.out.println(s))- Use
IntStream,LongStream,DoubleStreamwhen working with primitives to avoid boxing overhead.
- Prefer
collect(Collectors.toList())overtoArray()for most use cases.
- Use parallel streams cautiously — profile first, and only use them for genuinely large, CPU-bound workloads with stateless operations.
- The original collection is never modified by stream operations. Streams create new results.
13. Interview Notes
Q1: What is a Stream in Java?
A: A Stream is a sequence of elements supporting sequential and parallel aggregate operations. It is not a data structure — it does not store data. It operates on a data source (collection, array, etc.) and produces a result or side-effect. Introduced in Java 8 in the java.util.stream package.
Q2: What are the three steps of a Stream pipeline?
A:
- Create a stream from a data source
- Apply zero or more intermediate operations (filter, map, sorted, etc.)
- Apply exactly one terminal operation (collect, count, forEach, etc.)
Q3: What is the difference between intermediate and terminal operations?
| Intermediate | Terminal | |
|---|---|---|
| Return type | Stream | Result (List, value, void) |
| Execution | Lazy — not run until terminal is invoked | Triggers the pipeline |
| Count | Zero or more | Exactly one |
| Examples | filter, map, sorted, peek | collect, count, forEach, reduce |
Q4: What does "lazy" mean in the context of Streams?
A: Intermediate operations are lazy — they are not executed when declared. They are only executed when a terminal operation is invoked. This enables optimizations like short-circuiting (stopping early when the answer is found) and processing elements one at a time rather than materializing intermediate collections.
Q5: Can a stream be reused after the terminal operation?
A: No. Once a terminal operation is invoked, the stream is closed. Attempting to use it again throws IllegalStateException: stream has already been operated upon or closed. You must create a new stream from the source.
Q6: What is the difference between `map()` and `flatMap()`?
A:
map()applies a one-to-one transformation: each input element produces exactly one output element.flatMap()applies a one-to-many transformation and flattens the result: each input element produces a Stream of output elements, and all those streams are merged into one.
Use flatMap() when your source is a nested collection (e.g., List).>
Q7: What is the difference between `findFirst()` and `findAny()`?
A:
findFirst()always returns the first element in encounter order. It is deterministic.findAny()may return any element. In parallel streams, it returns whatever thread completes first, making it faster but non-deterministic.- In sequential streams, both typically return the same result.
Q8: What is the difference between `.stream()` and `.parallelStream()`?
A:
.stream()creates a sequential stream processed by a single thread in order..parallelStream()creates a parallel stream that splits the data and processes chunks concurrently using the Fork/Join pool and multiple CPU cores.
Q9: How does `sorted()` differ from other intermediate operations in terms of execution?
A: sorted() is a stateful intermediate operation. Unlike stateless operations (filter, map, peek) that can process elements one at a time, sorted() must collect all elements before it can produce any output, because it needs to compare all elements to determine their order. This breaks the element-by-element pipeline for that stage.
Q10: What is the Fork/Join pool and how does it relate to parallel streams?
A: The Fork/Join pool is a special thread pool designed for divide-and-conquer algorithms. Parallel streams use it internally:
- Fork: the Spliterator divides the source into smaller chunks recursively
- Join: results from all chunks are combined after processing
The pool uses work-stealing — idle threads steal tasks from busy threads to maximize CPU utilization.
Q11: What is a Spliterator?
A: A Spliterator (Splittable Iterator) is an interface that can both iterate over elements and split them for parallel processing. When .parallelStream() is called, the collection's spliterator() method is used, and trySplit() is called recursively to divide the data into chunks for parallel processing.
Q12: Does a Stream modify the original collection?
A: No. Stream operations never modify the original source. All operations create new streams or new collections as output. The source remains unchanged.
14. Practice Questions
Easy
- Create a stream from a list of integers and print only the even numbers.
- From a list of strings, find the count of strings with length greater than 5.
- From a list of integers, find the sum using
reduce. - Create a stream using
Stream.of()and collect it into a list. - From a list of integers, skip the first 3 elements and print the rest.
Medium
- Given a list of
Employeeobjects (with fieldsnameandsalary), find the names of all employees earning more than 50,000, sorted alphabetically. - Given a
List, flatten it into a single- >
Listand remove duplicates. - From a list of integers, find the maximum value using streams.
- From a list of strings, create a
Mapwhere the key is the string and the value is its length. - Use
Stream.iterate()to generate the first 10 multiples of 7.
Hard
- Given a list of employees, group them by department using
Collectors.groupingBy(). - Explain why the following code prints nothing, and fix it:
1 List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);2 nums.stream().filter(n -> n > 2).peek(System.out::println);- Write a parallel stream that computes the sum of squares of all integers from 1 to 1,000,000 and verify the result matches the sequential version.
- Why might the following parallel stream produce incorrect results?
1 List<Integer> results = new ArrayList<>();2 numbers.parallelStream().forEach(results::add);How would you fix it?
- Explain the output order of the following code and describe what happens step-by-step:
1 Arrays.asList(5, 1, 3, 2, 4)2 .stream()3 .filter(n -> n > 1)4 .map(n -> -n)5 .sorted()6 .forEach(System.out::println);15. Summary Quick Revision Bullets
- A Stream is a pipeline for processing data; it does not store data.
- Streams are created from collections, arrays,
Stream.of(),Stream.builder(), orStream.iterate(). - A stream pipeline has 3 steps: create stream → intermediate operations (0 or more) → terminal operation (exactly 1).
- Intermediate operations return a
Stream, are lazy, and are only executed when a terminal operation is invoked. - Terminal operations trigger execution, produce a result, and close the stream.
- Intermediate operations:
filter,map,flatMap,distinct,sorted,peek,limit,skip,mapToInt, etc. - Terminal operations:
forEach,collect,reduce,count,min,max,anyMatch,allMatch,noneMatch,findFirst,findAny,toArray. - Lazy evaluation means intermediate operations execute element-by-element only when a terminal operation triggers the pipeline.
- Streams process elements one at a time sequentially, passing each through each non-stateful operation before moving to the next element.
- Stateful operations (like
sorted,distinct) require all elements before they can produce output. - A stream is closed after the terminal operation. Attempting to reuse it throws
IllegalStateException. - Original data is never modified by stream operations.
- Parallel streams (
.parallelStream()) divide data using aSpliteratorand process chunks concurrently via the Fork/Join pool. - Parallel streams are useful for large, CPU-intensive, stateless operations. Avoid them for small datasets or operations with shared mutable state.
IntStream,LongStream,DoubleStreamare specialized primitive streams that avoid boxing overhead.Optionalis returned by operations likereduce,min,max,findFirst,findAnyto safely handle potentially-absent values.
End of Java Streams Study Guide
Practice & Implement
Apply what you learned in Java Streams
Given a list of sentences, split each into words, flatten to a single stream, count total words, and also find the longest word.
8 functional
Mastery check
How well can you recall this?
Finished this lesson?