🐦 Kotlin Intermediate

What is groupBy in Kotlin?

Answer

groupBy groups the elements of a collection by a key derived from each element, returning a Map<K, List<V>>. Example: val byDepartment = employees.groupBy { it.department } returns a map where each key is a department name and each value is the list of employees in that department. For getting only the first element per key, use associateBy { } instead. The result map is ordered by the first occurrence of each key. For multi-level grouping, chain groupBy calls on the resulting lists.