Bird
Raised Fist0
Kotlinprogramming~10 mins

Sorted and sortedBy in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Sorted and sortedBy
Start with List
↓
Choose sorting method
↓
sorted()
↓
Sort ascending
↓
Return new sorted list
↓
End
Start with a list, choose sorted() for natural order or sortedBy() to sort by a property, then get a new sorted list.
Execution Sample
Kotlin
val numbers = listOf(3, 1, 4)
val sortedNumbers = numbers.sorted()
val people = listOf(Person("Bob", 25), Person("Alice", 30))
val sortedByAge = people.sortedBy { it.age }
Sort a list of numbers in ascending order and a list of people by their age.
Execution Table
StepActionInput ListSorting MethodResulting List
1Start with numbers list[3, 1, 4]N/A[3, 1, 4]
2Call sorted() on numbers[3, 1, 4]sorted()[1, 3, 4]
3Start with people list[Person(Bob,25), Person(Alice,30)]N/A[Bob(25), Alice(30)]
4Call sortedBy { it.age } on people[Bob(25), Alice(30)]sortedBy { it.age }[Bob(25), Alice(30)]
5If reversed order needed, use sortedDescending or sortedByDescendingN/AN/AN/A
💡 All sorting calls return new lists; original lists remain unchanged.
Variable Tracker
VariableStartAfter sorted()After sortedBy()
numbers[3, 1, 4][3, 1, 4][3, 1, 4]
sortedNumbersN/A[1, 3, 4]N/A
people[Bob(25), Alice(30)][Bob(25), Alice(30)][Bob(25), Alice(30)]
sortedByAgeN/AN/A[Bob(25), Alice(30)]
Key Moments - 3 Insights
Why does the original list 'numbers' not change after calling sorted()?
Because sorted() returns a new list and does not modify the original list, as shown in execution_table row 2.
How does sortedBy decide the order of elements?
sortedBy uses the key selector function (like 'it.age') to compare elements, as shown in execution_table row 4.
What if you want to sort in descending order?
Use sortedDescending() or sortedByDescending() to get a new list sorted in reverse order.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'sortedNumbers' after step 2?
A[3, 1, 4]
B[1, 3, 4]
C[4, 3, 1]
DN/A
💡 Hint
Check the 'Resulting List' column in row 2 of execution_table.
At which step does the sorting use a property of objects instead of natural order?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look for 'sortedBy { it.age }' in the 'Sorting Method' column.
If we changed sortedBy { it.age } to sortedByDescending { it.age }, how would the 'Resulting List' in step 4 change?
A[Alice(25), Bob(30)]
B[Bob(25), Alice(30)]
C[Alice(30), Bob(25)]
DNo change
💡 Hint
Descending order reverses the sorted list by the key property.
Concept Snapshot
sorted() returns a new list sorted in ascending natural order.
sortedBy { key } returns a new list sorted by the given key selector.
Original lists stay unchanged.
Use sortedDescending or sortedByDescending for reverse order.
Both return new lists, do not modify original.
Full Transcript
This visual shows how Kotlin's sorted() and sortedBy() work. We start with a list, then call sorted() to get a new list sorted in ascending order. The original list stays the same. For objects, sortedBy lets us sort by a property, like age. The result is a new list sorted by that property. We also note that descending order versions exist. Variables track original and new lists. Key moments clarify why original lists don't change and how sorting keys work. The quiz checks understanding of these steps.

Practice

(1/5)
1. What does the sorted() function do in Kotlin?
easy
A. It sorts the original list in place and returns nothing.
B. It arranges elements randomly in a new list.
C. It returns a new list with elements arranged in natural ascending order.
D. It filters elements based on a condition.

Solution

  1. Step 1: Understand the purpose of sorted()

    The sorted() function creates a new list where elements are arranged in natural ascending order (numbers from smallest to largest, strings alphabetically).
  2. Step 2: Check if original list changes

    The original list remains unchanged because sorted() returns a new sorted list without modifying the original.
  3. Final Answer:

    It returns a new list with elements arranged in natural ascending order. -> Option C
  4. Quick Check:

    sorted() = new ascending list [OK]
Hint: sorted() always returns a new ascending list [OK]
Common Mistakes:
  • Thinking sorted() changes the original list
  • Confusing sorted() with filtering
  • Assuming sorted() arranges elements randomly
2. Which of the following is the correct syntax to sort a list of strings by their length using sortedBy in Kotlin?
easy
A. list.sortedBy { it.length }
B. list.sortedBy.length()
C. list.sortedBy(it.length)
D. list.sortedBy { length(it) }

Solution

  1. Step 1: Identify correct lambda syntax for sortedBy

    The sortedBy function takes a lambda expression that returns the property to sort by. The correct syntax is list.sortedBy { it.property }.
  2. 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.
  3. Final Answer:

    list.sortedBy { it.length } -> Option A
  4. Quick Check:

    sortedBy uses lambda with it.property [OK]
Hint: Use curly braces and 'it' to access property in sortedBy [OK]
Common Mistakes:
  • Using parentheses instead of curly braces
  • Calling length() as a function incorrectly
  • Passing property outside lambda
3. What is the output of the following Kotlin code?
val numbers = listOf(5, 3, 8, 1)
val sortedNumbers = numbers.sortedBy { it % 3 }
println(sortedNumbers)
medium
A. [1, 3, 5, 8]
B. [3, 6, 9, 12]
C. [1, 5, 3, 8]
D. [3, 1, 5, 8]

Solution

  1. Step 1: Calculate the sorting key for each element

    Calculate it % 3 for each number: 5 % 3 = 2, 3 % 3 = 0, 8 % 3 = 2, 1 % 3 = 1.
  2. 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].
  3. Final Answer:

    [3, 1, 5, 8] -> Option D
  4. Quick Check:

    sortedBy { it % 3 } = [3, 1, 5, 8] [OK]
Hint: Calculate sorting key for each element before sorting [OK]
Common Mistakes:
  • Sorting by values instead of keys
  • Confusing modulo results
  • Assuming sortedBy sorts original list
4. Identify the error in this Kotlin code snippet:
val fruits = listOf("apple", "banana", "cherry")
val sortedFruits = fruits.sortedBy(it.length)
println(sortedFruits)
medium
A. sortedBy cannot be used on lists of strings.
B. Missing curly braces around the lambda expression in sortedBy.
C. The list should be mutable to use sortedBy.
D. The println statement is incorrect.

Solution

  1. Step 1: Check syntax of sortedBy usage

    The sortedBy function requires a lambda expression inside curly braces, like { it.length }. The code uses parentheses without braces, which is incorrect.
  2. 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.
  3. Final Answer:

    Missing curly braces around the lambda expression in sortedBy. -> Option B
  4. Quick Check:

    sortedBy needs { } for lambda [OK]
Hint: Always use curly braces for lambda in sortedBy [OK]
Common Mistakes:
  • Using parentheses instead of curly braces for lambda
  • Thinking sortedBy needs mutable list
  • Misunderstanding println usage
5. Given a list of data class objects 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?
hard
A. persons.sortedWith(compareBy({ it.age }, { it.name }))
B. persons.sortedBy { it.age + it.name }
C. persons.sortedBy { it.name }.sortedBy { it.age }
D. persons.sortedByDescending { it.age }.sortedBy { it.name }

Solution

  1. Step 1: Understand multi-level sorting in Kotlin

    To sort by multiple properties, use sortedWith(compareBy(...)) passing lambdas for each property in priority order.
  2. Step 2: Analyze options

    persons.sortedWith(compareBy({ it.age }, { it.name })) correctly uses compareBy with 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.
  3. Final Answer:

    persons.sortedWith(compareBy({ it.age }, { it.name })) -> Option A
  4. Quick Check:

    Use sortedWith(compareBy(...)) for multi-level sort [OK]
Hint: Use sortedWith(compareBy(...)) for sorting by multiple keys [OK]
Common Mistakes:
  • Adding different types in sortedBy
  • Chaining sortedBy loses previous sort
  • Using sortedByDescending when ascending needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard