🔹 What is the Stream API?

The Stream API allows you to process collections of data (like filtering, mapping, sorting) in a declarative and efficient way.

✅ Think of a stream as a pipeline of operations applied to a sequence of elements.


🧱 Key Concepts

Concept Description
Stream A sequence of elements supporting sequential & parallel operations
Intermediate Operations Return a new stream (lazy evaluation) — e.g., map, filter
Terminal Operations Produces a result or side-effect — e.g., collect, forEach
Pipeline Chaining of operations in a readable flow

🔁 Stream Pipeline Structure

Collection.stream()
          .filter(...)     // Intermediate
          .map(...)        // Intermediate
          .collect(...)    // Terminal

✅ Real-Life Example

List<String> names = Arrays.asList("Aftab", "Neha", "Ravi", "Nitin");

List<String> filtered = names.stream()
                             .filter(name -> name.startsWith("N"))
                             .map(String::toUpperCase)
                             .collect(Collectors.toList());

System.out.println(filtered); // Output: [NEHA, NITIN]


🔧 Common Stream Methods

🧩 Intermediate Operations (do not trigger execution)

Method Purpose
filter() Filters elements by condition
map() Transforms each element
sorted() Sorts elements
distinct() Removes duplicates
limit(n) Keeps only first n elements
skip(n) Skips first n elements

🎯 Terminal Operations (triggers stream execution)

Method Purpose
forEach() Iterates over each element (side-effect)
collect() Converts stream to collection/list/map
count() Counts elements
reduce() Combines elements into one (sum, concat)
anyMatch() Checks if any element matches predicate

⚡ Stream vs Collection

Feature Collection Stream
Storage Stores elements Doesn’t store, just processes
Evaluation Eager (loads all elements) Lazy (runs only on terminal ops)
Mutability Can modify elements Immutable (produces new streams)
Multiple use Reusable Single-use (must recreate)
Parallel Support Manual with threads Easy with .parallelStream()

🔥 Parallel Stream Example

list.parallelStream()
    .filter(x -> x > 10)
    .forEach(System.out::println);

✅ Summary

Attribute Value
Package java.util.stream
Key Types Stream<T>, IntStream, DoubleStream
Core Ideas Functional-style, declarative pipelines
Best Used For Transforming & processing collections
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.