The groupingBy() extension function in Kotlin creates a Grouping source from a set to be used later with one of the group-and-fold operations, using the specified keySelector function to extract a key from each element.
The syntax of Set.groupingBy() extension function is:
fun <T, K> Set<T>.groupingBy(keySelector: (T) -> K): Grouping<T, K>
This groupingBy() extension function of Set creates a Grouping source from a collection to be used later with one of group-and-fold operations using the specified keySelector function to extract a key from each element.
Parameter | Optional/Required | Description |
---|---|---|
keySelector | required | A function that takes an element and returns the key for grouping. |
Set.groupingBy() returns value of type Grouping
.
Using groupingBy() to create a Grouping source from a set of integers by even and odd.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val grouping = numbers.groupingBy { if (it % 2 == 0) "Even" else "Odd" }
println(grouping)
}
Grouping source with keySelector: (kotlin.Int) -> kotlin.String
Using groupingBy() to create a Grouping source from a set of strings by their length.
For example,
fun main() {
val strings = setOf("one", "two", "three", "four", "five")
val grouping = strings.groupingBy { it.length }
println(grouping)
}
Grouping source with keySelector: (kotlin.String) -> kotlin.Int
Using groupingBy() to create a Grouping source from a set of integers by their parity (even/odd) with a custom key.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 6)
val grouping = numbers.groupingBy { if (it % 2 == 0) "Even" else "Odd" }
println(grouping)
}
Grouping source with keySelector: (kotlin.Int) -> kotlin.String
In this Kotlin tutorial, we learned about groupingBy() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.