The Stream API, introduced in Java 8, allows functional-style operations on collections of data. It provides a powerful and expressive way to process sequences of elements with operations like filter, map, reduce, and collect.
A Stream is a sequence of elements supporting functional-style operations.
Does not store data; it operates on a source (like Collection, Array, or I/O channel).
Can be sequential or parallel.
Key Characteristics:
No storage: Stream does not store elements; it processes them.
Functional in nature: Operations are declarative, not imperative.
Lazy evaluation: Operations like filter or map are executed only when terminal operation is invoked.
Possibility of parallel execution for improved performance.
Streams can be created from collections, arrays, or generators.
Return a new Stream, allowing method chaining.
Examples:
filter() → Select elements based on a condition
map() → Transform elements
sorted() → Sort elements
distinct() → Remove duplicates
Produce a result or side-effect, ending the stream pipeline.
Examples:
forEach() → Iterates elements
collect() → Converts stream to collection
reduce() → Aggregates elements
count() → Returns element count
Output:
Concise and readable code → Reduces boilerplate loops
Functional programming style → Supports operations like map, filter, reduce
Lazy evaluation → Improves performance
Parallel processing → Easily perform parallel operations
Works with collections, arrays, and I/O sources
Stream does not modify the source; it produces a new sequence of elements.
Operations can be chained to build pipelines.
Supports sequential and parallel streams.
Works closely with Lambda expressions for functional-style programming.
The Java Stream API provides a modern, functional approach to data processing, making code more readable, concise, and efficient. It is a cornerstone of Java 8+ programming, widely used in collections processing, file handling, and data transformations.
Take quizzes related to this topic and see where you stand!
Start Quiz Now