Reputation: 1086
I'm new to Kotlin and I'm trying to solve some problem. I have a list with the following object:
data class Route(duration: Int)
I want to create a map that will group those trips according to the range of the duration (e.g. 0-9 are single group, 10-19 the next, 20-29, and so on...)
for example, the result of this list:
listOf(Route(5), Route(7), Route(31))
should be the following map:
0..9 to listOf(Route(5), Route(7))
30..39 to listOf(Route(31))
I searched and I've seen that I can put the range into groupBy
- however, this is a const range. how can I group by different ranges?
Upvotes: 1
Views: 636
Reputation: 8096
You can use the groupBy function to do that.
fun createRangeOfTen(number: Int): IntRange {
val trunc = number / 10
val lowerBound = trunc * 10
val upperBound = lowerBound + 9
return lowerBound..upperBound
}
val list = listOf(
Route(5), Route(7), Route(31)
)
val map = list.groupBy({ createRangeOfTen(it.duration) }, { it })
println(map)
// {0..9=[Route(duration=5), Route(duration=7)], 30..39=[Route(duration=31)]}
Upvotes: 2