Sort family
Don't worry, we won't have to implement our own sort algorithm. This is not CS 101.
Having the list of people from the preceding find()
example, we would like to sort them by age:
val people = listOf(Person("Jane", "Doe", 19), Person("John", "Doe", 24), Person("John", "Smith", 23))
It is easily achieved with sortedBy()
:
println(people.sortedBy { it.age })
The preceding code prints the following output:
[Person(firstName=Jane, lastName=Doe, age=19), Person(firstName=John, lastName=Smith, age=23), Person(firstName=John, lastName=Doe, age=24)]
There's also sortedByDescending()
, which will reverse the order of the results:
println(people.sortedByDescending { it.lastName })
The preceding code prints the following output:
[Person(firstName=John, lastName=Smith, age=23), Person(firstName=John, lastName=Doe, age=24), Person(firstName=Jane, lastName=Doe, age=19)]
And if you want to compare by more than one parameter, use the combination of sortedWith
and compareBy
:
println(people.sortedWith(compareBy...