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]}

How to split sequences into subsets in Scala (groupBy, partition, splitAt, span)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.19, “How to Split Scala Sequences into Subsets (groupBy, partition, etc.)”


You want to partition a sequence into two or more different sequences (subsets) based on an algorithm or location you define.