2 2 Intermediate and Terminal Operations Explained
Intermediate and terminal operations are fundamental concepts in the Java Stream API. Understanding these operations is crucial for effectively processing collections of data in a functional style. This guide will delve into the key concepts, provide detailed explanations, and offer examples to enhance your understanding.
Key Concepts
1. Intermediate Operations
Intermediate operations transform a stream into another stream. They are lazy, meaning they do not process the elements until a terminal operation is invoked. Common intermediate operations include filter
, map
, and flatMap
.
2. Terminal Operations
Terminal operations produce a non-stream result, such as a primitive value, a collection, or no value at all. They trigger the processing of elements in the stream. Common terminal operations include forEach
, collect
, and reduce
.
Detailed Explanation
1. Intermediate Operations
Intermediate operations allow you to perform various transformations on the stream elements. They return a new stream that can be further processed by other intermediate or terminal operations.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class IntermediateOperationsExample { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); List<String> filteredNames = names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .collect(Collectors.toList()); filteredNames.forEach(System.out::println); } }
2. Terminal Operations
Terminal operations are the final step in a stream pipeline. They produce a result or a side-effect. Once a terminal operation is invoked, the stream cannot be reused.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TerminalOperationsExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream() .filter(n -> n % 2 == 0) .mapToInt(Integer::intValue) .sum(); System.out.println("Sum of even numbers: " + sum); } }
Examples and Analogies
Intermediate Operations
Think of intermediate operations as stages in a production line. Each stage processes the product (stream element) and passes it to the next stage. The final product is only assembled when the production line reaches the end (terminal operation).
Terminal Operations
Think of terminal operations as the final packaging and shipping of a product. Once the product is packaged (terminal operation is invoked), it is ready for delivery (result is produced), and the production line cannot be reused for the same product.