Java Stream reduce() operation with examples

 222 total views,  2 views today

Welcome to Java 8 series. In this tutorial, you will learn about java stream reduce() operation with examples.

reduce() is a part of the Stream pipeline and terminal operation. It belongs to the Stream interface.

  • Stream reduce() operation allows us to reduce the elements of the stream into a single result by applying a function repeatedly on the elements of the stream. This function allows applying certain logic(e.g sum, min, max) on the stream to reduce the element to a single result
  • reduce() returns a value.
  • Once reduce() is applied to a stream, it returns a result and the stream will be closed.
  • reduce() is a terminal operation and hence a stream cannot be reused.

There are three different varieties of Java 8 steam reduce() operation.

  1. reduce() operation with accumulator
  2. reduce() operation with identity and accumulator
  3. reduce() operation with identity, accumulator, and combiner.

Let us now see a simple example of each reduce() variant

reduce() operation with accumulator

Performs a reduction on the elements of the stream, using an accumulation function, and returns an Optional describing the reduced value.

Stream reduce() operation to sum elements of the stream

(Please keep reading I have explained the examples in detail)

Accumulator: Accumulator function accumulates the result of the applied function and produces a single result.

In this example, we have written a reduce function to sum of all elements of the stream.

public class StaticReference
{
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);

        Optional<Integer> result = list
                                   .stream()
                                   .reduce((i, j) -> i + j);
        System.out.println(result.get());
    }
}

Output

22

So how does stream reduce() work to get the sum?

reduce() operation takes the first two elements of the stream in the first iteration and sums it and produces the output.

i.e (4,5) -> (4+5) = 9

Now it takes the previous output and sums it with the next element of the stream.

(9,6) -> (9+6) = 15

Now again it takes the previous output and sums it with the next element of the stream.

(15,7) -> (15+7) = 22

So 22 is the final output.


1st iteration (4 + 5) -> 9
2nd iteration (9 + 6) -> 15
3rd iteration (15 + 7)-> 22

Sum = 22

Stream reduce() operation with accumulator to get the min element of the stream

In this example,we have written a reduce function to get minimum element of the stream.

public class StaticReference
{
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(4);
        list.add(5);
        list.add(1);
        list.add(7);

        Optional<Integer> result = list.stream().reduce((i, j) -> {
            if (i <= j)
                return i;
            else
                return j;
        });

    System.out.println(result.isPresent() ? result.get() : "no result");
    }
}

Output

1

So how does stream reduce() work to get the min?

reduce() operation takes the first two elements of the stream in the first iteration and finds the min and produces the output.

i.e (4,5) -> min(4,5) = 4

Now it takes the previous output and finds the min with the next element of the stream.

(4,1) -> min(4,1) = 1

Now again it takes the previous output and finds the min with the next element of the stream.

(1,7) -> min(1,7) = 1

So 1 is the final output.


1st iteration (4,5) -> 4
2nd iteration (4,1) -> 1
3rd iteration (1,7)-> 1

min = 1

Stream reduce() operation with accumulator to get max element of the stream

In this example, we have written a reduce function to get the maximum element of the stream.

public class StaticReference {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(4);
		list.add(51);
		list.add(1);
		list.add(7);

	Optional<Integer> result = list.stream().reduce((i, j) -> {
			if (i >= j)
				return i;
			else
				return j;
		});

System.out.println(result.isPresent() ? result.get() : "no result");
	}
}

Output

51

So how does stream reduce() work to get the max?

reduce() operation takes the first two elements of the stream in the first iteration and finds the max and produces the output.

i.e (4,51) -> max(4,51) = 51

Now it takes the previous output and finds the max with the next element of the stream.

(51,1) -> max(51,1) = 51

Now again it takes the previous output and finds the max with the next element of the stream.

(51,7) -> max(51,7) = 51

So 51 is the final output.


1st iteration (4,51) -> 51
2nd iteration (51,1) -> 51
3rd iteration (51,7)-> 1

max = 51

reduce() operation with identity and accumulator

Performs a reduction on the elements of the stream, using an accumulation function and identity(initial value), and returns a reduced value.

identity: Initial value to be used by the reduction function.
accumulator: Accumulator function accumulates the result of the applied function and produces a single result

In this example, we have written a reduce function with identity and accumulator to sum of all elements of the stream.

Identity is nothing but a initial value.In this example, initial value is 10. Sum of elements of list is 22. So result is 10 + 22 = 32

public class StaticReference {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(4);
		list.add(5);
		list.add(6);
		list.add(7);

		Integer result = list
				  .stream()
				  .reduce(10, (i, j) -> i + j);
		System.out.println(result);
	}
}

Output

32

reduce() operation with identity, accumulator, and combiner

This is a reduce() operation with three arguments identity(initial value), accumulator and combiner. This method is used only for the parallel stream.

public class StaticReference {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(4);
		list.add(5);
		list.add(6);
		list.add(7);

		Integer result = list
				 .stream()
				 .parallel()
			.reduce(10, (i, j) -> i + j, (a, b) -> a + b);

		System.out.println(result);
	}
}

Conclusion

reduce() operation is a terminal operation and it is used to reduce the stream into single result.

References :Official documentation

Thanks for reading. Please a comment and give us a thumbs up! 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.