Recall & Review
beginner
What does the
groupBy function do in Kotlin?It groups elements of a collection into a map, where each key is a category and the value is a list of elements belonging to that category.
Click to reveal answer
beginner
How do you specify the category for grouping when using
groupBy?You provide a lambda function that returns the key for each element, which determines the category it belongs to.
Click to reveal answer
beginner
Example: What is the result of
listOf(1, 2, 3, 4).groupBy { it % 2 }?A map grouping numbers by even or odd:
{0=[2, 4], 1=[1, 3]} where 0 means even and 1 means odd.Click to reveal answer
intermediate
Can
groupBy be used with custom objects?Yes, you can group custom objects by any property or computed value by providing a lambda that returns the grouping key.
Click to reveal answer
intermediate
What type does
groupBy return?It returns a
Map<K, List<T>> where K is the key type from the lambda and T is the element type.Click to reveal answer
What is the output type of
groupBy in Kotlin?✗ Incorrect
groupBy returns a map where each key maps to a list of elements in that group.
Which lambda expression groups a list of strings by their first letter?
✗ Incorrect
Grouping by the first letter uses it.first() in the lambda.
If you want to group numbers by whether they are positive or negative, which key selector is best?
✗ Incorrect
it > 0 returns true or false, grouping numbers by positive or not.
Can
groupBy be used on an empty list?✗ Incorrect
Grouping an empty list returns an empty map without error.
What happens if multiple elements have the same key in
groupBy?✗ Incorrect
All elements with the same key are grouped together in a list.
Explain how the
groupBy function works in Kotlin and give a simple example.Think about sorting items into labeled boxes based on a rule.
You got /4 concepts.
Describe a real-life scenario where you could use
groupBy to organize data.Imagine sorting your friends by their favorite color.
You got /4 concepts.