Grouping collections
Kotlin's collection framework allows you to group collections based on your requirements. For example, if you have a list of strings and want to group them with respect to their size, you can easily do that with the help of the groupBy
function, which groups a collection based on the logic provided and returns Map
with that group of collections.
So, the following is a short example:
fun main(args: Array<String>) { val list = 1.rangeTo(50).toList() println(list.groupBy { it%5 }) }
So, what we did here is as follows: we created a list of Int
containing numbers from 1
to 50
(both inclusive) then, we tried to group them based on their remnants when divided by 5
.
So, there should be five groups, from 0
to 5
, and each of them should contain 10 numbers. Let's check the following output to see if that happened or not:
So, the groupBy
function just worked as expected and returned Map<Int,List<Int>>
that contained the grouped list.