Collecting and Reducing Streams
Welcome to "Collecting and Reducing Streams"
Welcome to the "Collecting and Reducing Streams" lesson! Today, we'll explore two crucial terminal operations in Java Streams: collecting and reducing. These operations are essential tools for transforming and summarizing data, giving you the ability to handle more complex data processing tasks.
What You'll Learn
By the end of this lesson, you'll be able to:
- Collect stream elements into various data structures.
- Join stream elements into a single string.
- Perform reduction operations to compute sums, products, and more.
Up to this point, we have focused on using forEach to directly print stream elements, but what if you need to store or further manipulate the results? That's where collecting and reducing come into play.
These skills are essential for effectively transforming and summarizing data streams, a key part of many data processing tasks.
Practical Example with Collecting and Reducing
In this section, we'll break down some practical examples to better understand collecting and reducing operations in Java Streams. Each example builds on the last, demonstrating how these operations can be used to process and transform data.
Collecting to a List
First, we'll start with collecting elements of a stream into a list:
- Creating a Stream:
numbers.stream()converts the list to a stream. - Collecting Elements:
.collect(Collectors.toList())gathers all elements in the stream into a new list using a method reference. - Output: The
collectedListcontains[1, 2, 3, 4, 5].
In this example, we use a method reference (Collectors.toList()) to specify how we want to collect the elements of the stream.
Collecting to a String with Joining
Next, we'll see how to collect stream elements into a formatted string:
- Mapping to Strings:
.map(String::valueOf)transforms each integer into its string representation. - Joining Elements:
.collect(Collectors.joining(", "))collects all the strings into one, separated by ", ". - Output: The
joinedStringis"1, 2, 3, 4, 5".
Here, we're using a method reference (String::valueOf) to map each integer to a string. The Collectors.joining(", ") method is then used to concatenate these strings with a comma and space.
