Java Stream API Overview
⏱ Estimated reading time: 2 min
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.
1. What is a Stream?
-
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
filterormapare executed only when terminal operation is invoked. -
Possibility of parallel execution for improved performance.
2. Stream Creation
Streams can be created from collections, arrays, or generators.
From Collections
From Arrays
3. Stream Operations
A. Intermediate Operations
-
Return a new Stream, allowing method chaining.
-
Examples:
-
filter()→ Select elements based on a condition -
map()→ Transform elements -
sorted()→ Sort elements -
distinct()→ Remove duplicates
-
B. Terminal Operations
-
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
-
4. Example: Using Stream API
Output:
5. Advantages of Stream API
-
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
6. Key Points
-
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.
7. Conclusion
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.
Register Now
Share this Post
← Back to Tutorials