What if you could sort any list with just one simple command, no matter how messy it is?
Why Sorted and sortedBy in Kotlin? - Purpose & Use Cases
Imagine you have a messy list of your friends' names and ages, and you want to put them in order by age or alphabetically by name. Doing this by hand means writing lots of code to compare each friend one by one.
Manually sorting means writing long, complicated code that is easy to get wrong. It takes a lot of time and effort, and if the list changes, you have to rewrite or fix your code again.
Kotlin's sorted and sortedBy functions do the hard work for you. They quickly and safely arrange your list in the order you want with just one simple line of code.
val sortedList = list.sortedWith(compareBy { it.age })val sortedList = list.sortedBy { it.age }You can easily organize data in any order you want, making your programs cleaner and faster to write.
Sorting a list of products by price or sorting contacts by last name in a phone app becomes effortless and reliable.
Manual sorting is slow and error-prone.
sorted and sortedBy simplify sorting tasks.
They help you write cleaner and more readable code.
Practice
sorted() function do in Kotlin?Solution
Step 1: Understand the purpose of
Thesorted()sorted()function creates a new list where elements are arranged in natural ascending order (numbers from smallest to largest, strings alphabetically).Step 2: Check if original list changes
The original list remains unchanged becausesorted()returns a new sorted list without modifying the original.Final Answer:
It returns a new list with elements arranged in natural ascending order. -> Option CQuick Check:
sorted() = new ascending list [OK]
- Thinking sorted() changes the original list
- Confusing sorted() with filtering
- Assuming sorted() arranges elements randomly
sortedBy in Kotlin?Solution
Step 1: Identify correct lambda syntax for sortedBy
ThesortedByfunction takes a lambda expression that returns the property to sort by. The correct syntax islist.sortedBy { it.property }.Step 2: Check each option
list.sortedBy { it.length } uses{ it.length }which correctly accesses the length property of each string. Other options have syntax errors or incorrect usage.Final Answer:
list.sortedBy { it.length } -> Option AQuick Check:
sortedBy uses lambda with it.property [OK]
- Using parentheses instead of curly braces
- Calling length() as a function incorrectly
- Passing property outside lambda
val numbers = listOf(5, 3, 8, 1)
val sortedNumbers = numbers.sortedBy { it % 3 }
println(sortedNumbers)Solution
Step 1: Calculate the sorting key for each element
Calculateit % 3for each number: 5 % 3 = 2, 3 % 3 = 0, 8 % 3 = 2, 1 % 3 = 1.Step 2: Sort numbers by these keys
Sort by keys in ascending order: 0 (3), 1 (1), 2 (5), 2 (8). So sorted list is [3, 1, 5, 8].Final Answer:
[3, 1, 5, 8] -> Option DQuick Check:
sortedBy { it % 3 } = [3, 1, 5, 8] [OK]
- Sorting by values instead of keys
- Confusing modulo results
- Assuming sortedBy sorts original list
val fruits = listOf("apple", "banana", "cherry")
val sortedFruits = fruits.sortedBy(it.length)
println(sortedFruits)Solution
Step 1: Check syntax of sortedBy usage
ThesortedByfunction requires a lambda expression inside curly braces, like{ it.length }. The code uses parentheses without braces, which is incorrect.Step 2: Verify other options
sortedBy works on lists of strings, the list can be immutable, and println is correct. So only the lambda syntax is wrong.Final Answer:
Missing curly braces around the lambda expression in sortedBy. -> Option BQuick Check:
sortedBy needs { } for lambda [OK]
- Using parentheses instead of curly braces for lambda
- Thinking sortedBy needs mutable list
- Misunderstanding println usage
data class Person(val name: String, val age: Int), how would you sort the list first by age ascending, then by name alphabetically using Kotlin's sorting functions?Solution
Step 1: Understand multi-level sorting in Kotlin
To sort by multiple properties, usesortedWith(compareBy(...))passing lambdas for each property in priority order.Step 2: Analyze options
persons.sortedWith(compareBy({ it.age }, { it.name })) correctly usescompareBywith age first, then name. persons.sortedBy { it.age + it.name } incorrectly adds age and name (different types). persons.sortedBy { it.name }.sortedBy { it.age } sorts twice but second sort overrides first. persons.sortedByDescending { it.age }.sortedBy { it.name } sorts age descending, not ascending.Final Answer:
persons.sortedWith(compareBy({ it.age }, { it.name })) -> Option AQuick Check:
Use sortedWith(compareBy(...)) for multi-level sort [OK]
- Adding different types in sortedBy
- Chaining sortedBy loses previous sort
- Using sortedByDescending when ascending needed
Ready to prove it?
Pass the test and this pattern moves unknown
