Core Module
12 min forge
Java Stream API
Master functional-style operations on collections. Filter, map, reduce, and parallel streams.
Java Stream API
π‘οΈ What is the Stream API?
Introduced in Java 8, the Stream API allows you to process sequences of elements in a functional and declarative manner. It does not store data; instead, it conveys elements from a source (like a collection) through a pipeline of computational steps.
β° When to Use
- Bulk Data Operations: Filtering, sorting, and transforming large collections.
- Parallel Processing: Easily leveraging multi-core processors with
parallelStream(). - Declarative Code: Replacing imperative for-loops with more readable "What vs How" logic.
π Complexity & Performance
- Lazy Evaluation: Intermediate operations (like
filter) are not executed until a terminal operation (likecollect) is called. This avoids unnecessary passes over the data. - Overhead: For very small collections, a simple
for-loopmight be faster due to the overhead of stream creation. - Parallelism: Parallel streams have overhead for splitting and merging. Only use them when the task is computationally expensive enough to justify the overhead.
π» Code Example: Functional Pipeline
java Standardimport java.util.*; import java.util.stream.*; public class StreamDemo { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Edward"); // Filter names longer than 4 chars, convert to upper case, and collect List<String> result = names.stream() .filter(n -> n.length() > 4) .map(String::toUpperCase) .sorted() .collect(Collectors.toList()); System.out.println(result); // [ALICE, CHARLIE, DAVID, EDWARD] } }
β οΈ Interview Pitfalls
- Reuse Trap: A stream can only be operated on (traversed) once. Attempting to reuse a stream after a terminal operation throws
IllegalStateException. - Side Effects: Avoid modifying the source collection inside a stream operation. This leads to unpredictable behavior, especially in parallel streams.
- Ordering:
parallelStream()does not guarantee order unless you useforEachOrdered(). - Intermediate vs Terminal: Know that
peek()is an intermediate operation and won't run unless a terminal operation likecount()orcollect()is triggered.