Kotlin groupBy syntax and example

Here’s a quick example of how to use the Kotlin groupBy syntax on a list, with the result of each example shown in the comments:

val names = listOf("kim", "julia", "jim", "hala")

names.groupBy { it -> it.length }  //LinkedHashMap: {3=[kim, jim], 5=[julia], 4=[hala]}
names.groupBy({it}, {it.length})   //LinkedHashMap: {kim=[3], julia=[5], jim=[3], hala=[4]}

As shown in the comments, the result of each groupBy example is a LinkedHashMap.

The groupBy function uses the value returned by the lambda function to group the list’s elements, as shown. While I show a List here, this syntax works for all Kotlin iterable collections, including Array and others.