The groupBy() extension function in Kotlin groups elements of the original set by the key returned by the given keySelector function applied to each element, and returns a map where each group key is associated with a list of corresponding elements or values.
There are 2 variations for the syntax of Set.groupBy() extension function. They are:
fun <T, K> Set<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>>
Parameters
Parameter | Optional/Required | Description |
---|---|---|
keySelector | required | A function that takes an element and returns the key for grouping. |
This extension function groups elements of the original collection by the key returned by the given keySelector function applied to each element and returns a map where each group key is associated with a list of corresponding elements.
Returns value of type Map<K, List<T>>
.
fun <T, K, V> Set<T>.groupBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, List<V>>
Parameters
Parameter | Optional/Required | Description |
---|---|---|
keySelector | required | A function that takes an element and returns the key for grouping. |
valueTransform | optional | A function that takes an element and returns the value to be grouped. |
This extension function groups values returned by the valueTransform function applied to each element of the original collection by the key returned by the given keySelector function applied to the element and returns a map where each group key is associated with a list of corresponding values.
Returns value of type Map<K, List<V>>
.
Using groupBy() to group elements in a set of integers by even and odd.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val groupedByEvenOdd = numbers.groupBy { if (it % 2 == 0) "Even" else "Odd" }
println(groupedByEvenOdd)
}
{Odd=[1, 3, 5], Even=[2, 4, 6]}
Using groupBy() to group elements in a set of strings by their length.
For example,
fun main() {
val strings = setOf("one", "two", "three", "four", "five")
val groupedByLength = strings.groupBy { it.length }
println(groupedByLength)
}
{3=[one, two], 5=[three], 4=[four, five]}
Using groupBy() to group elements in a set of integers by even and odd, and transforming the values to their squares.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val groupedByEvenOddWithSquares = numbers.groupBy(
keySelector = { if (it % 2 == 0) "Even" else "Odd" },
valueTransform = { it * it }
)
println(groupedByEvenOddWithSquares)
}
{Odd=[1, 9, 25], Even=[4, 16, 36]}
In this Kotlin tutorial, we learned about groupBy() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.