Kotlin Array - groupBy() Function



The Kotlin array groupBy() function is used to group elements of an original array based on a specified key selector function. It returns a Map where keys are the results of the key selector function, and values are lists of elements corresponding to each key.

The returned map preserves the entry iteration order of the keys produced from the original array.

Syntax

Following is the syntax of Kotlin array groupBy() function −

fun <T, K> Iterable<T>.groupBy( keySelector: (T) -> K): Map<K, List<T>>

Parameters

This function accepts a selector: (T) -> (k) function. Which is lambda function that defines how to select a key for each element in the array. 'T' is the type of element in an array and 'k' is the type of key returned by the selector function

Return value

This function returns a map.

Example 1

Following is the basic example to demonstrate the use of groupBy() function −

fun main(args: Array<String>){
   val words = arrayOf("tutorialspoint", "tutorix", "kotlin", "Hyderabad", "Noida", "India")

   val byLength = words.groupBy { it.length }
   
   println(byLength)
   println(byLength.keys)
   println(byLength.values)
}

Output

On execution of the above code we get the following result −

{14=[tutorialspoint], 7=[tutorix], 6=[kotlin], 9=[Hyderabad], 5=[Noida, India]}
[14, 7, 6, 9, 5]
[[tutorialspoint], [tutorix], [kotlin], [Hyderabad], [Noida, India]]

Example 2

Now, let's see another example. Here, we are creating a pair list and grouping all element with their role by using of the groupBy()

fun main(args: Array<String>) {
   val nameToTeam = listOf("Aman" to "Developer", "Amansha" to "Devloper", "tuorialspoint" to "EdTech", "tutorix" to "Tuition center")
   val namesByTeam = nameToTeam.groupBy({ it.second }, { it.first })
   println(namesByTeam)
}

Output

After execution of the above code we get the following output −

{Developer=[Aman], Devloper=[Amansha], EdTech=[tuorialspoint], Tuition center=[tutorix]}

Example 3

The below example using the classes and object. We then create an array with objects and use the groupBy() function to group the array's objects by class −

import kotlin.reflect.KClass
fun main(args: Array<String>){
   val people = arrayOf(
       Employer("John", 42),
       Employer("Mark", 38),
       Employee("Sunny", 27, 35000.0),
       Employee("Joseph", 32, 41000.0)
   )
   //groupingBy
   val byType: Map<KClass<*>, List<Any>> = people.groupBy{ it.javaClass.kotlin }
   println("Employers: ${byType[Employer::class]}")
   println("Employees: ${byType[Employee::class]}")
}
//classes
data class Employer(val name: String, val age: Int)
data class Employee(val name: String, val age: Int, val salaray: Double)

Output

The above code produce following output −

Employers: [Employer(name=John, age=42), Employer(name=Mark, age=38)]
Employees: [Employee(name=Sunny, age=27, salaray=35000.0), Employee(name=Joseph, age=32, salaray=41000.0)]
kotlin_arrays.htm
Advertisements