Middle
When does the stream execution start in Java?
sobes.tech AI
Answer from AI
Stream execution begins when a terminal operation is invoked.
Terminal operations:
forEach/forEachOrderedtoArrayreducecollectcountanyMatch/allMatch/noneMatchfindFirst/findAnymin/max
Intermediate operations, such as filter, map, sorted, are lazy and only describe the data processing pipeline without actually performing any actions until a terminal operation is called.
Example:
// Data source: list of numbers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Intermediate operations define the pipeline but are not executed
Stream<Integer> processedStream = numbers.stream()
.filter(n -> {
// This code will not execute until a terminal operation is invoked
System.out.println("Filtering: " + n);
return n % 2 == 0;
})
.map(n -> {
// This code will not execute until a terminal operation is invoked
System.out.println("Mapping: " + n);
return n * 2;
});
// Terminal operation - triggers the pipeline execution
List<Integer> result = processedStream.collect(Collectors.toList());
// Output will be:
// Filtering: 1
// Filtering: 2
// Mapping: 2
// Filtering: 3
// Filtering: 4
// Mapping: 4
// Filtering: 5