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 (like collect) is called. This avoids unnecessary passes over the data.
  • Overhead: For very small collections, a simple for-loop might 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 Standard
import 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

  1. Reuse Trap: A stream can only be operated on (traversed) once. Attempting to reuse a stream after a terminal operation throws IllegalStateException.
  2. Side Effects: Avoid modifying the source collection inside a stream operation. This leads to unpredictable behavior, especially in parallel streams.
  3. Ordering: parallelStream() does not guarantee order unless you use forEachOrdered().
  4. Intermediate vs Terminal: Know that peek() is an intermediate operation and won't run unless a terminal operation like count() or collect() is triggered.