Advertisement
Google Ad Slot: content-top
Java Stream API
The Stream API in Java is used for functional-style operations on collections of data. It was introduced in Java 8 and provides a powerful way to process sequences of elements.
Key Features of Stream API
Declarative – Focuses on what to do, not how to do it.
Lazy Evaluation – Operations are performed only when necessary.
Functional Programming – Uses lambda expressions and method references.
Parallel Processing – Improves performance on large data sets.
Non-Mutable – Does not modify the original collection.
Creating Streams:
Stream Operations:
There are two types of operations in Stream API:
- Intermediate Operations – Return another Stream (e.g.,
filter(),map(),sorted()). - Terminal Operations – Produce a result (e.g.,
forEach(),collect(),reduce()).
Method |
Description |
|---|---|
Filters elements based on a condition. |
|
Collects results into a list. |
|
Transforms elements. |
|
Sorts elements. |
|
Counts elements in the stream. |
|
Combines all elements into one. |
|
Checks conditions on elements. |
Filtering Elements (filter()) and Collecting Elements (collect()) :
- Filters elements based on a condition.
- Converts the Stream into a List, Set, or Map.
Transforming Elements (map()):
Modifies each element in the stream.
Sorting Elements (sorted()):
Sorts elements in natural order or custom order.
Counting Elements (count()):
Counts the number of elements in the stream.
Reducing Elements (reduce()):
Combines all elements into a single value.
Checking Conditions (anyMatch(), allMatch()):
Parallel Streams for Performance:
Java provides parallel streams for multi-threaded processing.