Intermediate operations Terminal operations
Description
A stream supports two types of operations:
- Intermediate operations
- Terminal operations
Intermediate operations are also called lazy operations.
Terminal operations are also called eager operations.
A lazy operation does not process the elements until an eager operation is called on the stream.
An intermediate operation on a stream produces another stream.
Streams link operations to create a stream pipeline.
Example
In the following code filter() and map() are all lazy operations. While reduce() is eager operation.
import java.util.Arrays;
import java.util.List;
//from ww w . j a v a2s. com
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.filter(n -> n % 2 == 1)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println(sum);
}
}
The code above generates the following result.