Middle
What are intermediate operations in the Stream API and how do they work?
sobes.tech AI
Answer from AI
Intermediate Operations in Java Stream API are operations that transform one stream into another stream. They are lazy, meaning they are executed only when a terminal operation is invoked.
Key characteristics:
- Return a Stream: The result of an intermediate operation is always a new stream.
- Lazy: They do not execute immediately after being called but only when a terminal operation is performed. This allows for optimization of stream processing, handling elements as needed.
- Can be chained: Multiple intermediate operations can be linked in a chain.
Examples of intermediate operations:
filter(): Selects elements that match a predicate.// Filters even numbers stream.filter(n -> n % 2 == 0)map(): Transforms each element into another type or value.// Converts strings to their length stream.map(String::length)sorted(): Sorts stream elements.// Sorts numbers in ascending order stream.sorted()distinct(): Removes duplicates.// Keeps only unique elements stream.distinct()limit(): Limits the number of elements in the stream.// Keeps only the first 5 elements stream.limit(5)skip(): Skips a specified number of initial elements.// Skips the first 3 elements stream.skip(3)
Stream processing is based on a pipeline: each element passes through a sequence of intermediate operations before being processed by a terminal operation. Lazy evaluation can avoid unnecessary computations. For example, if filter and limit are used, elements can be filtered and processed until the limit is reached without processing all source stream elements.