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.
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 }
| Step | Action | Input List | Sorting Method | Resulting List |
|---|---|---|---|---|
| 1 | Start with numbers list | [3, 1, 4] | N/A | [3, 1, 4] |
| 2 | Call sorted() on numbers | [3, 1, 4] | sorted() | [1, 3, 4] |
| 3 | Start with people list | [Person(Bob,25), Person(Alice,30)] | N/A | [Bob(25), Alice(30)] |
| 4 | Call sortedBy { it.age } on people | [Bob(25), Alice(30)] | sortedBy { it.age } | [Bob(25), Alice(30)] |
| 5 | If reversed order needed, use sortedDescending or sortedByDescending | N/A | N/A | N/A |
| Variable | Start | After sorted() | After sortedBy() |
|---|---|---|---|
| numbers | [3, 1, 4] | [3, 1, 4] | [3, 1, 4] |
| sortedNumbers | N/A | [1, 3, 4] | N/A |
| people | [Bob(25), Alice(30)] | [Bob(25), Alice(30)] | [Bob(25), Alice(30)] |
| sortedByAge | N/A | N/A | [Bob(25), Alice(30)] |
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.