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:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Collecting to a list
List<Integer> collectedList = numbers.stream()
                                     .collect(Collectors.toList());
System.out.println("Collected List: " + collectedList);
  • 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 collectedList contains [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:

// Collecting to a string with joining
String joinedString = numbers.stream()
                             .map(String::valueOf)
                             .collect(Collectors.joining(", "));
System.out.println("Joined String: " + joinedString);
  • 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 joinedString is "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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal