Interview question
What is the difference between intermediate and terminal operations in Java Streams? Java Streams में intermediate और terminal operations में क्या अंतर है?
Answer
| Type | Returns | Execution | Examples |
|---|---|---|---|
| Intermediate | Another Stream | Lazy - not executed until a terminal op is called | filter, map, sorted, distinct, limit |
| Terminal | A non-stream result or void | Eager - triggers the whole pipeline to run | collect, forEach, reduce, count, anyMatch |
import java.util.stream.*;
List<Integer> numbers = List.of(5, 3, 8, 1, 9, 2);
// Chaining multiple intermediate operations - nothing executes yet
Stream<Integer> pipeline = numbers.stream()
.filter(n -> n > 2) // intermediate
.map(n -> n * 2) // intermediate
.sorted(); // intermediate
System.out.println('Pipeline built, nothing executed yet');
// Only when a TERMINAL operation is called does the pipeline actually run
List<Integer> result = pipeline.collect(Collectors.toList()); // terminal - triggers execution
System.out.println(result); // [6, 10, 16, 18]
// A stream can only have ONE terminal operation - after that it's consumed
// pipeline.count(); // IllegalStateException - stream already consumed
// Short-circuiting operations - some terminals stop early once satisfied
boolean hasLarge = numbers.stream()
.peek(n -> System.out.println('Checking: ' + n))
.anyMatch(n -> n > 8);
// Stops as SOON as it finds a match - doesn't process every remaining element
// limit() - an intermediate operation that's also short-circuiting
List<Integer> firstThree = numbers.stream()
.filter(n -> n > 0)
.limit(3) // stops the pipeline early once 3 elements pass
.collect(Collectors.toList());
// Why laziness matters for performance: filter+map+limit(3) on a huge
// stream only processes as many elements as needed to satisfy limit(3),
// not the entire source collection| Type | Return | Execution | उदाहरण |
|---|---|---|---|
| Intermediate | दूसरा Stream | Lazy | filter, map, sorted |
| Terminal | Non-stream result | Eager, पूरी pipeline चलाता है | collect, forEach, reduce |
import java.util.stream.*;
List<Integer> numbers = List.of(5, 3, 8, 1, 9, 2);
Stream<Integer> pipeline = numbers.stream()
.filter(n -> n > 2)
.map(n -> n * 2)
.sorted();
System.out.println('Pipeline बनी, अभी execute नहीं हुई');
List<Integer> result = pipeline.collect(Collectors.toList()); // terminal
System.out.println(result); // [6, 10, 16, 18]
// pipeline.count(); // IllegalStateException
boolean hasLarge = numbers.stream()
.peek(n -> System.out.println('Checking: ' + n))
.anyMatch(n -> n > 8);
// Match मिलते ही रुक जाता है
List<Integer> firstThree = numbers.stream()
.filter(n -> n > 0)
.limit(3)
.collect(Collectors.toList());Was this answer clear?