In Java streams, intermediate and terminal operations are the two main types of operations that can be performed on a stream.
- Intermediate Operations:
- Intermediate operations are operations that are applied to a stream and produce a new stream as a result. These operations are typically used for transforming, filtering, or sorting the elements of a stream. Intermediate operations are lazy, meaning they are not executed until a terminal operation is invoked on the stream.
Some common intermediate operations in Java streams include:
- map: Applies a function to each element and transforms it into another type.
- filter: Filters out elements based on a specified condition.
- sorted: Sorts the elements of the stream based on a comparator.
- distinct: Removes duplicate elements from the stream.
- limit: Limits the number of elements in the stream to a specified size.
- flatMap: Transforms each element into a stream and flattens the result.
- Terminal Operations:
- Terminal operations are operations that are applied to a stream and produce a non-stream result, such as a value, a collection, or a side effect. When a terminal operation is invoked, the intermediate operations are executed on the stream elements to produce the final result.
Some common terminal operations in Java streams include:
- forEach: Performs an action on each element of the stream.
- collect: Collects the elements of the stream into a collection or a single value.
- reduce: Combines the elements of the stream into a single value using a specified operation.
- count: Returns the count of elements in the stream.
- anyMatch, allMatch, noneMatch: Check if any, all, or none of the elements satisfy a given condition.
- min, max: Returns the minimum or maximum element of the stream based on a comparator.
It's important to note that a stream pipeline typically consists of a sequence of intermediate operations followed by a terminal operation. The intermediate operations are executed in a lazy manner, only when the terminal operation is triggered. This lazy evaluation allows for optimized and efficient processing of large data sets.