Effective Kotlin Item 53: Consider using groupingBy instead of groupBy
As a part of numerous complex collection processing, we need to group elements. Here are a few tasks, that require this operation:
- Count the number of users in each city, based on a list of users.
- Find the number of points received by each team, based on a list of players.
- Find the best option in each category, based on the list of options.
The easiest way to solve this problem is by using
groupBy function. It returns a
Map<K, List<V>>, where
V is the type of elements on the collection we started from, and
K is the type we are mapping to. So if we have a list of
User that we group by an id of type
String, then the returned map is
Map<String, List<User>>. In other words,
groupBy is dividing our collection into a smaller one for each key. This is how this function can be used to solve the above problems:
Those are good solutions. When we use
groupBy, we receive a
Map as a result, and we can use all the different methods defined on it. This makes
groupBy a really nice intermediate step. I would even say, it should be preferred for convenience and readability.
On the other hand, if we are dealing with some performance-critical parts of our code, this step is not necessary. It takes some time to create as many collections as many categories we have. Instead, we could use the function
groupingBy, that is not doing any additional operations. It just wraps the iterable, together with specified key selector.
Grouping can be considered a bit like a map from key to a list of elements, but it has much fewer operations supported. Although since using it might be an important optimization, let's analyze what are the options.
The first problem (counting users per city), can be solved easily. There is already
eachCount function on the Kotlin Standard Library. We just need to use it, to have a map from the city to the number of users.
Finding the number of points received by each team is a bit harder. We can use
fold function. It is like a
fold on iterable, but it is having a separate accumulator for each key. So calculating the number of points per team is very similar to calculating the number of all the points in a collection.
It would make sense to extract an extension function to calculate a sum on each group. We might call it
Finally, the last problem. We need to find the biggest element in the group. We might use
fold, but this would require some "zero" value, which we don't have. Instead, we can use
reduce, that just starts from the first element. Its lambda has one more parameter, that is the reference to the key of the group (in the below example we don't use it, so there is
Now you might notice, that we could have used
reducein the previous problem as well. That is right, and such a solution would be more efficient. I just wanted to present both options.
Again, we can extract an extension function.
The last important function from the stdlib defined on
aggregate. It is very similar to
reduce. It iterates over all the elements and aggregates for each key. Its operation has 4 parameters: key of the current element; accumulator (also per element) or
null for the first element with this key; reference to the element; boolean saying if it is the first element for this key. This is how our last problem can be solved using
groupBy is a part of many collection processing processes. It is convenient to use, as it returns a
Map, that has plenty of useful functions. Its alternative is
groupingBy, which is better for performance, but generally harder to use. It currently supports the following functions:
aggregate. Using them, we can define other functions we might need, like in this chapter we defined