Kotlin Kotlin Collections 2 — Questions and Answers
Question 1: What does `groupBy` return in Kotlin?
- A List of pairs
- A Map where keys are the grouping criteria and values are lists of elements (Correct answer)
- A Set of keys
- A sorted list
Correct answer: A Map where keys are the grouping criteria and values are lists of elements
`groupBy` returns a `Map<K, List<T>>` where each key maps to a list of elements that share that key.
Question 2: Which function finds the first element matching a predicate in Kotlin?
- firstOrNull (Correct answer)
- findFirst
- first
- filter
Correct answer: firstOrNull
`firstOrNull` returns the first element matching the predicate, or `null` if no element matches, avoiding a NoSuchElementException.
Question 3: How do you sort a list in descending order in Kotlin?
- list.sort()
- list.sortedDescending() (Correct answer)
- list.reversed()
- list.sortByDescending()
Correct answer: list.sortedDescending()
`sortedDescending()` returns a new list sorted in descending order without modifying the original list.
Question 4: What does the `any` function do on a Kotlin collection?
- Returns the first element
- Returns true if at least one element satisfies the predicate (Correct answer)
- Returns all elements matching the predicate
- Returns the count of matching elements
Correct answer: Returns true if at least one element satisfies the predicate
`any` returns `true` if at least one element in the collection satisfies the given predicate.
Question 5: What is a Sequence in Kotlin and how does it differ from a List?
- Sequences are sorted lists
- Sequences are lazy; operations are applied one element at a time instead of creating intermediate lists (Correct answer)
- Sequences are thread-safe collections
- Sequences store unique elements only
Correct answer: Sequences are lazy; operations are applied one element at a time instead of creating intermediate lists
Kotlin `Sequence` is a lazy collection that processes elements one by one through a chain of operations, avoiding intermediate collection allocations.
Question 6: Which function removes duplicate elements from a Kotlin list?
- unique()
- toSet()
- distinct() (Correct answer)
- deduplicate()
Correct answer: distinct()
`distinct()` returns a new list with all duplicate elements removed, preserving the order of first occurrence.
What does `groupBy` return in Kotlin?