Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
How do Java Streams work, and what is the difference between intermediate and terminal operations?
junior LevelCode ExamplejavaCore Language
In Simple Words: A Stream is a sequence of elements supporting functional-style pipeline operations:
- Intermediate Operations: Lazy; return a new Stream without executing (e.g.,
filter(),map(),sorted(),distinct()). Execution is deferred until a terminal operation is called. - Terminal Operations: Eager; triggers the processing pipeline and produces a result or side-effect (e.g.,
collect(),forEach(),reduce(),count(),findFirst()). Once consumed, a Stream cannot be reused.
java
List<String> topEarners = employees.stream()
.filter(e -> e.salary() > 100_000) // Intermediate (lazy)
.sorted(Comparator.comparing(Employee::salary).reversed()) // Intermediate
.map(Employee::name) // Intermediate
.limit(5) // Intermediate
.collect(Collectors.toList()); // Terminal (triggers execution)