3.2.3 Terminal Operations Explained
Terminal operations in Java Streams are the final steps that trigger the processing of the stream pipeline. They produce a result or a side-effect, such as collecting elements into a collection, reducing them to a single value, or performing an action on each element. Understanding terminal operations is crucial for effectively utilizing Java Streams.
Key Concepts
1. Collecting Elements
Terminal operations like collect()
allow you to gather stream elements into a collection or other data structure. The Collectors
class provides various methods to specify how elements should be collected.
Example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<String> filteredNames = names.stream() .filter(name -> name.startsWith("A")) .collect(Collectors.toList()); System.out.println(filteredNames); // Output: [Alice]
2. Reducing Elements
Reduction operations like reduce()
combine stream elements into a single result. This can be used for tasks such as summing numbers, concatenating strings, or finding the maximum value.
Example
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream() .reduce(0, (a, b) -> a + b); System.out.println(sum); // Output: 15
3. Performing Actions
Terminal operations like forEach()
allow you to perform an action on each element of the stream. This is useful for side-effects, such as printing elements or updating a state.
Example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .forEach(System.out::println); // Output: Alice, Bob, Charlie
Examples and Analogies
Think of terminal operations as the final steps in a manufacturing process. Once the conveyor belt (stream) has processed all the items (elements), you need to package them (collect), calculate the total output (reduce), or inspect each item (forEach). These final steps ensure that the data is transformed or utilized as needed.
By mastering terminal operations, you can effectively process and utilize data streams in your Java SE 11 applications, making your code more efficient and expressive.