Sequences: Implementation of the groupBy

Explanation of how the groupBy function works in sequences

Max Sidorov
1 min readOct 27, 2023

Children’s riddle, find 10 differences

Implementation of sequences

public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Sequence<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}

Implementation of collections

public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}

Answer: The difference is only in the generic type.

The implementation of this function in collections and sequences is identical. This function clearly demonstrates that our performance gain is achieved solely by avoiding the copying of intermediate results, in essence, the copying of arrays.

You can learn more from my sequences performance study “Measuring sequences”

--

--

Max Sidorov

Android lead at SberDevices. I like programming and exploring the internals of Kotlin.