0
0
Kotlinprogramming

Sorted and sortedBy in Kotlin

Choose your learning style9 modes available
Introduction

We use sorted and sortedBy to arrange items in a list in order. This helps us find things faster or show them nicely.

When you want to show a list of names in alphabetical order.
When you need to organize numbers from smallest to largest.
When you want to sort objects by one of their properties, like sorting people by age.
When you want to prepare data for reports or display in a neat order.
Syntax
Kotlin
val sortedList = list.sorted()
val sortedByList = list.sortedBy { item -> item.property }

sorted() works on lists of items that can be compared directly, like numbers or strings.

sortedBy { } lets you choose a property or value to sort by, useful for objects.

Examples
This sorts numbers from smallest to largest.
Kotlin
val numbers = listOf(3, 1, 4, 2)
val sortedNumbers = numbers.sorted()
This sorts strings alphabetically.
Kotlin
val names = listOf("Bob", "Alice", "Eve")
val sortedNames = names.sorted()
This sorts a list of people by their age from youngest to oldest.
Kotlin
data class Person(val name: String, val age: Int)

val people = listOf(
    Person("Bob", 30),
    Person("Alice", 25),
    Person("Eve", 35)
)

val sortedByAge = people.sortedBy { it.age }
Sample Program

This program shows how to sort numbers, names, and a list of people by age using sorted() and sortedBy.

Kotlin
data class Person(val name: String, val age: Int)

fun main() {
    val numbers = listOf(5, 2, 9, 1)
    val sortedNumbers = numbers.sorted()
    println("Sorted numbers: $sortedNumbers")

    val names = listOf("Charlie", "Alice", "Bob")
    val sortedNames = names.sorted()
    println("Sorted names: $sortedNames")

    val people = listOf(
        Person("Dave", 40),
        Person("Carol", 22),
        Person("Eve", 30)
    )
    val sortedPeopleByAge = people.sortedBy { it.age }
    println("People sorted by age:")
    for (person in sortedPeopleByAge) {
        println("${person.name} - ${person.age}")
    }
}
OutputSuccess
Important Notes

sorted() returns a new list and does not change the original list.

You can also use sortedDescending() or sortedByDescending { } to sort in reverse order.

Summary

sorted() arranges items in natural order (numbers or strings).

sortedBy { } arranges items by a chosen property.

Both create new sorted lists without changing the original.