0
0
Kotlinprogramming~20 mins

Sorted and sortedBy in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sorted Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using sorted()?
Consider the following Kotlin code that sorts a list of numbers. What will be printed?
Kotlin
val numbers = listOf(5, 3, 8, 1)
val sortedNumbers = numbers.sorted()
println(sortedNumbers)
A[8, 5, 3, 1]
B[1, 5, 3, 8]
C[5, 3, 8, 1]
D[1, 3, 5, 8]
Attempts:
2 left
💡 Hint
The sorted() function returns a new list with elements in ascending order.
Predict Output
intermediate
2:00remaining
What does sortedBy return for this list of strings?
Given this Kotlin code, what will be the output?
Kotlin
val fruits = listOf("apple", "banana", "pear", "kiwi")
val sortedByLength = fruits.sortedBy { it.length }
println(sortedByLength)
A["kiwi", "pear", "apple", "banana"]
B["pear", "kiwi", "apple", "banana"]
C["banana", "apple", "pear", "kiwi"]
D["apple", "banana", "pear", "kiwi"]
Attempts:
2 left
💡 Hint
sortedBy sorts elements based on the value returned by the lambda.
🔧 Debug
advanced
2:00remaining
Why does this Kotlin code cause a compilation error?
Look at this Kotlin code snippet. Why does it cause a compilation error?
Kotlin
val numbers = listOf(1, 2, 3)
val sorted = numbers.sortedBy { it > 2 }
println(sorted)
AsortedBy expects a selector returning a Comparable, but 'it > 2' returns Boolean which is not Comparable
BsortedBy cannot be used on lists of integers
CThe lambda syntax is incorrect; it should be 'it -> it > 2'
DsortedBy requires the list to be mutable
Attempts:
2 left
💡 Hint
Check the return type of the lambda passed to sortedBy.
🧠 Conceptual
advanced
2:00remaining
How does sorted() differ from sortedBy() in Kotlin?
Which statement best describes the difference between sorted() and sortedBy()?
Asorted() modifies the original list; sortedBy() returns a new list
Bsorted() sorts only numbers; sortedBy() sorts only strings
Csorted() sorts elements naturally; sortedBy() sorts elements using a selector function
Dsorted() sorts in descending order; sortedBy() sorts in ascending order
Attempts:
2 left
💡 Hint
Think about how you tell Kotlin what to sort by.
Predict Output
expert
3:00remaining
What is the output of this Kotlin code using sortedBy with nulls?
Consider this Kotlin code that sorts a list with nullable strings. What will be printed?
Kotlin
val names: List<String?> = listOf("Anna", null, "Bob", "", null)
val sortedNames = names.sortedBy { it?.length ?: -1 }
println(sortedNames)
A[null, null, "", "Bob", "Anna"]
B["", "Bob", "Anna", null, null]
C[null, "", null, "Bob", "Anna"]
D["Anna", "Bob", "", null, null]
Attempts:
2 left
💡 Hint
Look at how nulls are handled with the Elvis operator ?: in the selector.