AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Reduce in Java Stream

In this new post, we will tackle and demonstrate Reduce in Java Stream with Examples.

The Java Stream API provides various functional operations for working with Streams in Java. One of those operations is Reduce, which allows us to obtain a single result from a stream.

Before we dive into the examples, let’s go over some basic concepts:

Concepts of Java Stream Reduce

To achieve our final unique result, we will make use of the following elements:

  • Identity: It is the initial value in the process of converting to a single value, or if there are no more values, the final value.
  • Accumulator: It is responsible for processing the values and accumulating the result.
  • Combiner: The combiner is used to combine the partial result obtained when the reduction is parallelized.

Now that we have a clearer understanding, let’s move on to some examples:

Stream Reduce in Java

The best way to understand Reduce and the aforementioned concepts is to see them through examples. For that, let’s sum a list of numbers.

List<Integer> numbers = List.of(1,2,3,4,5,6,7,8);

int number = numbers.stream()
        .reduce(0, (acumulator, element)-> acumulator + element);

System.out.println("Total: "+ number);

Output:

Total: 36

In the previous example, we can see the usage of identity and accumulator. The first one is the value we start with, in this case, the identity is 0, and the second one stores the partial results, which we have named accumulator in this case.

Next, let’s take a look at an example of Reduce with Strings. In the following example, we will return a String that concatenates only the letter ‘A’.

    List<String> letters = List.of("A","B","C","D","A","E","A");

    letters.stream()
        .reduce("", (acumulator, element)-> {
          if (element.equalsIgnoreCase("A")) {
            return acumulator+element;
          }
          return acumulator;
        });

System.out.println("Letters are:  "+ letters);

Output:

Letters are:: AAA

We can see that the treatment with String and Integer is quite similar. In the latter, we have added some complexity by including an “if” statement within the reduce function.

Using Combiner in Stream Reduce

Now let’s see the usage of Combiner. As mentioned before, this element is used when the Reduce function is used with parallelStream. However, it could also be used with Stream as an auxiliary or additional function to the process. In this post, we will focus on parallelStream.

When using parallelStream in Java Streams, we are processing small streams that need to be combined later. That’s why we make use of Combiner. It is important to note that parallelStream is recommended when dealing with large amounts of data. If the Stream is not very large, the performance may worsen.

List<Car> cars = Arrays.asList(new Car("Mustang", 10), new Car("Megane", 35), new Car("Toledo", 21);

int number = cars.stream()
  .reduce(0, (partialResult, car) -> partialResult + car.getAge(), Integer::sum);

System.out.println("Total: "+ number); //67

Conclusion

In this post, we have explored another usage that the Java Stream API provides us to process information and obtain a single result: the use of Reduce.

If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!

Leave a Reply

Your email address will not be published. Required fields are marked *