0
0
Kotlinprogramming~5 mins

GroupBy for categorization in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AMap&lt;Key, List&lt;Element&gt;&gt;
BList&lt;Key&gt;
CSet&lt;Element&gt;
DArray&lt;Element&gt;
Which lambda expression groups a list of strings by their first letter?
Alist.groupBy { it.first() }
Blist.groupBy { it.length }
Clist.groupBy { it.toUpperCase() }
Dlist.groupBy { it.last() }
If you want to group numbers by whether they are positive or negative, which key selector is best?
AgroupBy { it % 2 }
BgroupBy { it == 0 }
CgroupBy { it.toString() }
DgroupBy { it > 0 }
Can groupBy be used on an empty list?
ANo, it throws an exception.
BYes, it returns an empty map.
CYes, it returns null.
DNo, it returns an empty list.
What happens if multiple elements have the same key in groupBy?
AAn error is thrown.
BOnly the first element is kept.
CThey are collected into the list for that key.
DOnly the last element is kept.
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.