How to Calculate Aggregate of a Collection In Java
finding min, max, average, count from the java collection
Originally Published @ https://asyncq.com/
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.
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
- we can use stream API and use max() and min() operation to achieve max/min value.
Reduce over Stream
- Another way is to use reduce operation and perform max/min using java Math API.
Map over Stream
- If we want to calculate average and count we can map to int or double to calculate average or count.
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.