0
0
Kotlinprogramming~15 mins

Sorted and sortedBy in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Sorted and sortedBy
What is it?
In Kotlin, sorted and sortedBy are functions used to arrange collections in order. sorted arranges elements based on their natural order, like numbers from smallest to largest. sortedBy lets you choose a specific property or rule to sort by, like sorting people by age. Both help organize data so it's easier to find or use.
Why it matters
Sorting helps us make sense of data by putting it in order, just like organizing books on a shelf by title or author. Without sorting, finding what you need would be slow and confusing. sorted and sortedBy make sorting easy and flexible in Kotlin, saving time and reducing mistakes.
Where it fits
Before learning sorted and sortedBy, you should understand Kotlin collections like lists and basic functions. After mastering these, you can explore more advanced collection operations like filtering, grouping, and custom sorting with comparators.
Mental Model
Core Idea
sorted arranges items by their natural order, while sortedBy arranges items based on a chosen property or rule.
Think of it like...
Imagine you have a box of mixed playing cards. sorted is like sorting them by their face value from lowest to highest, while sortedBy is like sorting them by their suit color or type instead.
Collection: [3, 1, 4, 2]

sorted():
  Step 1: Compare elements
  Step 2: Arrange ascending
  Result: [1, 2, 3, 4]

sortedBy { property }:
  Step 1: Extract property from each element
  Step 2: Compare properties
  Step 3: Arrange elements by property
  Result: Elements ordered by chosen property
Build-Up - 6 Steps
1
FoundationUnderstanding Kotlin Collections
🤔
Concept: Learn what collections are and how lists store multiple items.
Collections in Kotlin are groups of items stored together. A list is a common collection that keeps items in order. For example, val numbers = listOf(3, 1, 4, 2) holds four numbers in a list.
Result
You can access and work with multiple items as a group.
Knowing collections is essential because sorting works on these groups of items.
2
FoundationNatural Order Sorting with sorted
🤔
Concept: sorted arranges items by their natural order, like numbers ascending or strings alphabetically.
Using sorted on a list like listOf(3, 1, 4, 2) returns a new list sorted from smallest to largest: [1, 2, 3, 4]. It works on types that have a natural order, such as numbers and strings.
Result
[1, 2, 3, 4]
Understanding natural order sorting helps you quickly organize simple data without extra rules.
3
IntermediateCustom Sorting with sortedBy
🤔Before reading on: do you think sortedBy changes the original list or returns a new sorted list? Commit to your answer.
Concept: sortedBy lets you sort items based on a property you choose, like sorting people by age.
If you have a list of people with names and ages, you can sort them by age using sortedBy { it.age }. This returns a new list ordered by the age property, from youngest to oldest.
Result
List of people sorted by age.
Knowing how to sort by properties lets you organize complex data in meaningful ways.
4
Intermediatesorted vs sortedBy Differences
🤔Before reading on: do you think sortedBy can be used without a lambda function? Commit to yes or no.
Concept: sorted uses natural order, sortedBy uses a selector function to pick what to sort by.
sorted works only on items that can be compared directly, like numbers or strings. sortedBy requires a lambda to extract a value from each item to sort by, like a person's age or a product's price.
Result
Clear understanding of when to use each function.
Distinguishing these functions prevents confusion and errors when sorting different data types.
5
AdvancedSorting Stability and Multiple Criteria
🤔Before reading on: do you think sortedBy keeps the order of equal elements? Commit to yes or no.
Concept: sortedBy is stable, meaning it keeps the original order for items with equal keys. You can chain sorting by multiple properties.
If two people have the same age, sortedBy keeps their original order. To sort by age then name, use sortedBy { it.age }.thenBy { it.name }. This orders first by age, then by name within the same age.
Result
Sorted list respecting multiple criteria with stable ordering.
Understanding stability and chaining helps create precise and predictable sorting.
6
ExpertPerformance and Lazy Sorting Considerations
🤔Before reading on: do you think sorted and sortedBy modify the original list or create new ones? Commit to your answer.
Concept: sorted and sortedBy create new sorted lists and do not change the original. For large data, consider lazy sequences to avoid unnecessary sorting.
Both functions return new lists, so the original stays unchanged. Sorting large collections eagerly can be costly. Using sequences with sorted or sortedBy delays sorting until needed, improving performance.
Result
Efficient sorting with control over when sorting happens.
Knowing how sorting affects performance and data immutability is key for writing efficient Kotlin code.
Under the Hood
sorted and sortedBy internally use Kotlin's standard library sorting algorithms, typically a variant of merge sort or TimSort, which are stable and efficient. sorted compares elements directly using their Comparable interface. sortedBy extracts keys using the provided lambda, then sorts elements based on those keys. Both create new lists to keep the original data unchanged.
Why designed this way?
Kotlin favors immutability and safety, so these functions return new sorted lists instead of changing originals. Stability in sorting preserves order of equal elements, which is important for predictable results. Using lambdas in sortedBy offers flexibility to sort complex data without extra boilerplate.
Original List
  │
  ▼
[Elements]
  │
  ├─ sorted() ──► Sort by natural order ──► New Sorted List
  │
  └─ sortedBy { key } ──► Extract keys ──► Sort by keys ──► New Sorted List
Myth Busters - 4 Common Misconceptions
Quick: Does sortedBy change the original list or return a new one? Commit to your answer.
Common Belief:sortedBy sorts the original list in place.
Tap to reveal reality
Reality:sortedBy returns a new sorted list and leaves the original list unchanged.
Why it matters:Modifying the original list unexpectedly can cause bugs and data inconsistencies.
Quick: Can sorted be used to sort by a property like age? Commit to yes or no.
Common Belief:sorted can sort by any property directly without extra code.
Tap to reveal reality
Reality:sorted only sorts by natural order of elements, not by properties; sortedBy is needed for property-based sorting.
Why it matters:Using sorted incorrectly leads to compile errors or wrong sorting results.
Quick: Does sortedBy guarantee the order of equal elements stays the same? Commit to yes or no.
Common Belief:sortedBy does not guarantee stable sorting; equal elements may reorder.
Tap to reveal reality
Reality:sortedBy is stable and preserves the order of equal elements.
Why it matters:Assuming instability can lead to unnecessary code complexity or bugs.
Quick: Is sorting with sortedBy always fast regardless of data size? Commit to your answer.
Common Belief:sortedBy is always efficient and fast for any data size.
Tap to reveal reality
Reality:Sorting large collections eagerly can be slow; lazy sequences can improve performance.
Why it matters:Ignoring performance can cause slow apps or crashes with big data.
Expert Zone
1
sortedBy uses stable sorting algorithms, which is crucial when sorting by multiple criteria in sequence.
2
sorted and sortedBy return new lists, preserving immutability, which helps avoid side effects in concurrent or functional code.
3
Using sortedBy with complex keys can impact performance; caching keys or using sequences can optimize this.
When NOT to use
Avoid sorted and sortedBy when working with huge datasets that require incremental or partial sorting; instead, use specialized data structures like priority queues or databases with indexing.
Production Patterns
In real-world Kotlin apps, sortedBy is often combined with filtering and mapping to prepare data for UI display. Developers also chain sortedBy and thenBy for multi-level sorting, and use sequences to handle large or streaming data efficiently.
Connections
Comparator Interface
sortedBy builds on the idea of comparing elements by keys, similar to how Comparator defines custom comparison rules.
Understanding Comparator helps grasp how sortedBy can be customized beyond natural order.
Functional Programming
sortedBy uses lambda functions to select sorting keys, reflecting functional programming principles of passing behavior as data.
Knowing functional programming concepts clarifies why sortedBy is flexible and expressive.
Library Cataloging Systems
Sorting books by title, author, or genre in a library is like using sorted and sortedBy to organize data by different properties.
Seeing sorting in libraries helps appreciate why flexible sorting is essential in software too.
Common Pitfalls
#1Trying to sort a list of objects with sorted without implementing Comparable.
Wrong approach:val people = listOf(Person("Alice", 30), Person("Bob", 25)) val sortedPeople = people.sorted()
Correct approach:val sortedPeople = people.sortedBy { it.age }
Root cause:sorted requires elements to have a natural order via Comparable; objects without it must be sorted by properties.
#2Expecting sortedBy to modify the original list in place.
Wrong approach:val numbers = mutableListOf(3, 1, 2) numbers.sortedBy { it } // expecting numbers to be sorted now
Correct approach:val sortedNumbers = numbers.sortedBy { it } // use sortedNumbers for sorted data
Root cause:sortedBy returns a new list and does not change the original collection.
#3Using sortedBy with a heavy computation inside the lambda repeatedly.
Wrong approach:val sorted = list.sortedBy { expensiveFunction(it) }
Correct approach:val keys = list.map { expensiveFunction(it) } val sorted = list.zip(keys).sortedBy { it.second }.map { it.first }
Root cause:Lambda in sortedBy is called multiple times; caching results avoids repeated expensive calls.
Key Takeaways
sorted arranges collections by their natural order, while sortedBy sorts by a chosen property using a lambda.
Both functions return new sorted lists and do not modify the original collections, preserving immutability.
sortedBy is stable, keeping the order of equal elements, which is important for multi-level sorting.
Using sortedBy with complex or large data requires attention to performance and may benefit from caching or lazy sequences.
Understanding these sorting functions helps organize data clearly and efficiently in Kotlin programs.