Kotlin List groupingBy()
Syntax & Examples
Syntax of List.groupingBy()
The syntax of List.groupingBy() extension function is:
fun <T, K> Iterable<T>.groupingBy( keySelector: (T) -> K ): Grouping<T, K>
This groupingBy() extension function of List 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.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing strings representing various fruits. - We use the
groupingBy
function to create aGrouping
source by grouping the fruits based on the first letter of each fruit, converted to uppercase. - The resulting
Grouping
source can be used later with group-and-fold operations. - We print the resulting
Grouping
source to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "orange", "grape");
val result = list.groupingBy { it.first().toUpperCase() }
println(result);
}
Output
MainKt$main$$inlined$groupingBy$1@3498ed
2 Example
In this example,
- We define a data class
Person
with propertiesname
andage
. - We create a list named
list
containing instances ofPerson
with different names and ages. - We use the
groupingBy
function to create aGrouping
source by grouping the persons by their names. - The resulting
Grouping
source can be used later with group-and-fold operations. - We print the resulting
Grouping
source to standard output.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val list = listOf(
Person("Alice", 20),
Person("Bob", 25),
Person("Alice", 30)
)
val result = list.groupingBy { it.name }
println(result);
}
Output
MainKt$main$$inlined$groupingBy$1@1a407d53
3 Example
In this example,
- We create a list named
list
containing strings representing various fruits. - We use the
groupingBy
function to create aGrouping
source by grouping the fruits based on their lengths. - The resulting
Grouping
source can be used later with group-and-fold operations. - We print the resulting
Grouping
source to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "orange", "grape")
val result = list.groupingBy { it.length }
println(result);
}
Output
MainKt$main$$inlined$groupingBy$1@3498ed
Summary
In this Kotlin tutorial, we learned about groupingBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.