Run across this very interesting but one year old presentation by Brian Goetz - in the slide linked he presents an aggregateBy()
method supposedly in the Stream API, which is supposed to aggregate the elements of a list (?) to a map (given a default initial value and a method manipulating the value (for duplicate keys also) - see next slide in the presentation).
Apparently there is no such method in the Stream API. Is there another method that does something analogous in Java 8 ?
Let's say we have a list of employees with their department and salary and we want the total salary paid by each department.
There are several ways to do it and you could for example use a
toMap
collector to aggregate the data per department:Example:
As often with streams, there are several ways to get the desired result, for example:
For reference, the Person class:
The aggregate operation can be done using the
Collectors
class. So in the video, the example would be equivalent to :The
groupingBy
method will give you aMap<String, List<Document>>
. Now you have to use a downstream collector to sum all the page count for each document in theList
associated with each key.This is done by providing a downstream collector to
groupingBy
, which issummingInt
, resulting in aMap<String, Integer>
.They give basically the same example in the documentation where they compute the sum of the employees' salary by department.
I think that they removed this operation and created the
Collectors
class instead to have a useful class that contains a lot of reductions that you will use commonly.This particular Javadoc entry is about the closest thing I could find on this piece of aggregation in Java 8. Even though it's a third party API, the signatures seem to line up pretty well - you provide some function to get values from, some terminal function for values (zero, in this case), and some function to combine the function and the values together.
It feels a lot like a Collector, which would offer us the ability to do this.
The idea then is that we group on the author's name for each entry in our list, and add up the total page numbers that the author has into a
Map<String, Integer>
.