Java Stream API Reduce Function

Dec 20th, 2020


Java logo

Java Stream API

The Java Stream API is a tool released with Java 8 that allows us to stream and transform collections. Java streams, along with the use of anonymous lambda expressions, gives Java developers a taste of functional programming.

With functions like map, reduce and filter, you can perform almost any transformation that you could desire. From lists of JPA entities, to lists of integers, the Java Stream API has you covered.

Reduce

All this talk of Java streams brings us back to the focus of the reduce function. With the reduce function, you can transform an entire collection into one element. The most common use of reduce is to calculate a sum or average.

Consider the following class


public class Sales {

  //all args constructor

  private final Long totalSales;

  private final double amount;

  private final Date date;

  //getters
  //setters

}

This class represents the sales at a store for a given day. A good application of reduce would be to calculate sales averages for a given date range. Notice it is best to use immutable objects, and create new ones as we go. This gives us an extra layer of thread safety among other things.

The reduce function takes a lambda expression called an accumulator as an argument. The accumulator takes two arguments, the accumulated object, and the current element, and returns the new accumulated object.


(accumulatedElement, currentElement) -> {
  accumatedElement + currentElement;
}

The above would generate the sum of elements in a collection.

Back to our daily sales average


Sale sum = listOfDailySales.stream().reduce((accumulated, current) -> {
  new Sales(accumulated.getTotalSales() + current.getTotalSales(), accumulated.getAmount() + current.getAmount(), current.getDate());
})

Sale average = new Sale(sum.getTotalSales() / listOfDailySales.size(), sum.getAmount / listOfDailySales.size(), sum.getDate());

There you have it! Notice, since the Sale class is immutable, we must always create a new one. This is best practice.

Conclusion

In conclusion, the Java Stream API has many functions, including reduce, that allow you to perform nearly any transformation on a collection. If you are not using the Java Stream API now, you should be.

Comments




Navagation