Sort collection by multiple fields in Kotlin
sortedWith
+ compareBy
(taking a vararg of lambdas) do the trick:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
You can also use the somewhat more succinct callable reference syntax:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
Use sortedWith
to sort a list with Comparator
.
You can then construct a comparator using several ways:
compareBy
,thenBy
construct the comparator in a chain of calls:list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
compareBy
has an overload which takes multiple functions:list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))