Sitemap

Reduce in Java Stream

5 min readApr 9, 2024

--

In this write up, let’s explore the “reduce” method in Java Stream. Synonyms for “reduce” include diminish, lessen, or decrease something.So what Java is trying to reduce or lessen or decrease. In order to answer this question, we need to understand on what object does a reduce method can be used and how to use it and reduce our stress of understanding the reduce function. Let’s dive into the definition.

Press enter or click to view image in full size

The “reduce” method operates on a stream object, which can source data from a collection, array, generator function, or I/O Streams. It executes a reduction operation on the stream’s elements, yielding a reduced value as the output.

As per the above definition, it makes use of a reduction operation and apply this reduction operation to reduce the elements into reduced value.This reduction operation is called as an accumulator function or associative accumulator function.

Let’s check out the method signature of the reduce method in Stream Class

Optional<T> reduce(BinaryOperator<T> accumulator);

Reduce Method accepts a BinaryOperator<T> as an argument and returns a Optional<T> . T -> Signifies the Type of Element in the Stream. For Example if we are applying the reduction in the Stream of Integers, then the T corresponds to Integer. We know the Accumulator function has two characteristics, a. Associative b. Accumulative. Lets try to understand them.

Associative Function.

An associative function refers to a mathematical operation where changing the grouping of elements does not alter the result.

Addition and Multiplication are Associative Function

(a+b) + c = a + (b+c)

(a*b) * c = a * (b*c)

Subtraction cannot be considered as a Associative Function because

(a-b) — c != a — (b-c).
For example, (5–3) — 2 is not the same as 5 — (3–2), as the first expression evaluates to 0 while the second evaluates to 4.

Accumulative Function.

An accumulative function is a mathematical or computational operation that progressively adds or accumulates values as it processes data.

So Let’s dive into some code to understand these definition. Let’s take a list and try to add all the numbers in the list and finally return the total sum of the list.

public static void main(String[] args) {
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
BinaryOperator<Integer> summationAccumulationFunction =(Integer accumulator,Integer currentElement) -> accumulator + currentElement;
Optional<Integer> sum = numbers.reduce(summationAccumulationFunction);
System.out.println("Sum: " + sum);
}

In the given example, we’re working with a “numbers” Stream Object and applying a BinaryOperator Function, a type of BiFunction where both the parameter and return types match. The accumulator parameter stores the ongoing results processed thus far, while currentElement indicates the element currently being processed. To handle an empty Stream, the return type for this reduction is Optional<T>.

Get sam rubin’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s see the other overloaded methods of Stream.

T reduce(T identity, BinaryOperator<T> accumulator);

We do have an identity parameter as an additional value in this reduce method. “identity” parameter provides the initial value for an reduction operation and it has one rule in it.

Rule for Identity => accumulator.apply(identity,T) == T

Let’s break down the rule described above. It states that when any element <E> in the stream is used in a reduction operation along with the identity value, it should always return that element <E> as the result. For example, in summation, adding any number N to zero always returns N. Therefore, 0 is the Identity or Initial Value for summation. Similarly, in multiplication, 1 is the identity value.

This method returns an element of type T. Because of the identity value, it will be returned as a response if the stream is empty.

Based on the methods discussed earlier, we can reduce a Stream of type <T> into a reduced value of type <T>, specifically when working with primitive types. However, if we have requirements to reduce type <T> into type <U>, we would need an additional function that performs this transformation during reduction from <T> to <U>, and then combines the reduced <U>.

Final Overloaded Method in the reduce operation.

<U> U reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner);

In the provided method signature, there’s an additional BiFunction parameter responsible for transforming values from type T to type U. Here, type T represents the elements in the stream. The rule for the identity value remains similar to the previous one, but this time it’s applied to the combiner instead of the accumulator.

Rule for Identity => combiner.apply(identity,U) == U

Let’s see an simple example for the above use case. We have a requirement to count the number of letters in a Stream of String.

public static void main(String[] args) {
Stream<String> words = Stream.of("hello","world","learning","streams");
Integer totalLetterCount = words.reduce(0,
(Integer accumulator, String word)
-> accumulator += word.length(),
(Integer combinerOne,Integer combinerTwo) -> combinerOne + combinerTwo);
System.out.println(totalLetterCount);
}

In the provided code, the second parameter to the reduce opertation shows a BiFunction that takes an Integer as its first parameter <U>, a String as its second parameter <T>, and returns an Integer <U>. This allows us to reduce the stream of type T into a reduced value of type <U>.

Let’s explore an example using a custom object. Imagine we have a list of transactions, and our goal is to determine the total transaction amount for each transaction type. In this scenario, we’ll work with Transaction objects of type T, compute the total amount for each transaction type, and then return the results as a HashMap containing the transaction type as the key and the corresponding total amount as a Double value.

package org.example;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;

public class Transaction {
private String type;
private double amount;

public Transaction(String type, double amount) {
this.type = type;
this.amount = amount;
}

public String getType() {
return type;
}

public double getAmount() {
return amount;
}

@Override
public String toString() {
return "Transaction{" +
"type='" + type + '\'' +
", amount=" + amount +
'}';
}
}

class TransactionMain {
public static void main(String[] args) {
List<Transaction> transactions = Arrays.asList(
new Transaction("Sale", 100.0),
new Transaction("Purchase", 50.0),
new Transaction("Sale", 200.0),
new Transaction("Sale", 150.0),
new Transaction("Purchase", 75.0)
);

// Calculate total amount for "Sale" transactions
BiFunction< HashMap<String, Double>, ? super Transaction, HashMap<String, Double>> accumulatorMap = new BiFunction<HashMap<String, Double>, Transaction, HashMap<String, Double>>() {
@Override
public HashMap<String, Double> apply(HashMap<String, Double> stringDoubleHashMap, Transaction transaction) {
Double currentValue = stringDoubleHashMap.getOrDefault(transaction.getType(),0.0d);
stringDoubleHashMap.put(transaction.getType(), currentValue+transaction.getAmount());
return stringDoubleHashMap;
}
};

BinaryOperator<HashMap<String, Double>> combiner = (HashMap<String, Double> stringDoubleHashMap, HashMap<String, Double> stringDoubleHashMap2) -> {
stringDoubleHashMap.putAll(stringDoubleHashMap2);
return stringDoubleHashMap;
};

HashMap<String,Double> totalSaleAmount = transactions.stream()
.reduce(new HashMap<>(), accumulatorMap,combiner );

System.out.println(totalSaleAmount);

}
}

--

--