Server Side Kotlin-10

Server Side Kotlin-10


2 min read

The groupBy() method in Kotlin is used to group elements of a collection based on a specified key. It operates on various collections like lists and returns a map where each group key is associated with a list of elements that share the same key. This groups elements by their lengths, resulting in a map where keys are lengths, and values are lists of corresponding elements.
groupBy() is a extension functions for grouping collection elements. It takes a lambda function and returns a Map, where each key is the lambda result and the corresponding value is the List of elements on which this result is returned.

KeySelector Function: The method takes a keySelector function, which is applied to each element to determine its key for grouping
groupBy() can be called with a second lambda argument – a value transformation function, which is key selector. In groupBy() with two lambdas, the keys produced by keySelector function are mapped to the List of the elements .

val games = listOf("unity", "unreal", "godot", "bevy")

println(games.groupBy { it.first().uppercase() })
println(games.groupBy(keySelector = { it.first() }, valueTransform = { it.uppercase() }))


{U=[unity, unreal], G=[godot], B=[bevy]}

{u=[UNITY, UNREAL], g=[GODOT], b=[BEVY]}

Namely, Grouping supports the following operations:

eachCount() counts the elements of every group.

fold() and reduce() perform fold and reduce operations for every group but as a separate collection .

aggregate() applies a given operation subsequently to every elements in each group and returns the result.

val games = listOf("unity", "unreal", "godot", "bevy")

println(games.groupingBy { it.first() }.eachCount())


{u=2, g=1, b=1}