Published in


How to Calculate Aggregate of a Collection In Java

finding min, max, average, count from the java collection

Originally Published @


We often have to compute aggregates over a collection of records, that maybe count users by per day, max order size across all the orders, or min number of customer ratings across all the orders delivered.

If you are using java, there are various ways to compute these aggregates including traditional style with imperative style or more modern way with Java streams API.

In this article let’s explore various ways to compute these aggregates across list of numbers as an example.

Imperative style

This style is the traditional way of computing aggregates across records. we use for each loop to iterate over each record and compare it with the current max/min value and then by the end of the loop our min/max variable is finally updated with the result that we want.

Java Collections API

  • Java Collections API also provide method such as max() and min()

Java 8 and Beyond

  • After the release of Java 8, we have many ways to calculate aggregates using streams API.

Max() & Min() Over Stream

Reduce over Stream

  • Another way is to use reduce operation and perform max/min using java Math API.

Map over Stream

Using Collectors API

  • Collectors API provides a bunch of methods to calculate max/min/average and count.
  • Additionally Collectors API also provides summarizing method that provides aggregates as an output results.


  • In this article, we discussed various methods that as a java developer we can use to calculate aggregates such as min/max/count/average over the list of numbers.
  • We can of course use these methods in the collection of any objects.
  • Java streams provide a more readable approach over imperative style code to calculate aggregates.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suraj Mishra

Suraj Mishra


Google Cloud Certified Professional Data Engineer | Backend Engineering @ Rakuten Card | Blogs @