Consider this Kotlin code that groups a list of words by their first letter. What will be printed?
val words = listOf("apple", "banana", "apricot", "blueberry", "cherry") val grouped = words.groupBy { it.first() } println(grouped)
Remember that groupBy creates a map where keys are the grouping criteria and values are lists of items matching that key.
The groupBy function groups words by their first character. So all words starting with 'a' are grouped together, and so on.
Given this Kotlin code, what will be printed?
val numbers = listOf(1, 2, 3, 4, 5, 6) val grouped = numbers.groupBy { if (it % 2 == 0) "even" else "odd" } println(grouped)
Look at the string keys used in the groupBy lambda.
The lambda returns "even" or "odd" strings, so the map keys are those strings with lists of numbers accordingly.
Look at this Kotlin code that tries to group a list of strings by length but causes a compilation error. What is the cause?
val words = listOf("cat", "dog", "bird") val grouped = words.groupBy { length } println(grouped)
Check how to access the length property of each string inside the lambda.
Inside the lambda, 'it' refers to each string. You must write 'it.length' to access the length property. Writing just 'length' causes an error because 'length' is not defined in that scope.
Given this code, how many keys will the resulting map have?
val items = listOf("red", "green", "blue", "yellow", "black") val grouped = items.groupBy { it.length } println(grouped.keys.size)
Count the distinct lengths of the strings in the list.
The lengths are: red(3), green(5), blue(4), yellow(6), black(5). Distinct lengths are 3, 4, 5, 6, so 4 groups.
What will this Kotlin code print?
val words = listOf("ant", "ape", "bat", "bear", "cat", "car") val grouped = words.groupBy { it.first() }.mapValues { it.value.size } println(grouped)
Look at how mapValues transforms the grouped map.
The groupBy groups words by first letter, then mapValues replaces each list with its size. Each letter has exactly 2 words, so the counts are 2.