To sort a collection by multiple fields in Kotlin, you can use the sortedWith
function along with a custom comparator. Here's an example:
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(
Person("John", 25),
Person("Alice", 30),
Person("Bob", 20),
Person("Alice", 25),
Person("John", 30)
)
val sortedPeople = people.sortedWith(compareBy(Person::name, Person::age))
for (person in sortedPeople) {
println("${person.name}, ${person.age}")
}
}
In this example, we have a Person
class with two fields: name
and age
. We create a list of Person
objects called people
.
To sort the people
list by both name
and age
, we use the sortedWith
function and pass it a comparator created using the compareBy
function. The compareBy
function takes the properties or fields that you want to sort by, in the order of priority. In this case, we sort by name
first and then by age
.
The resulting sortedPeople
list will be sorted based on the defined criteria. We then iterate over the sorted list and print the name
and age
of each person.
The output of the above code will be:
Alice, 25 Alice, 30 Bob, 20 John, 25 John, 30
As you can see, the list is sorted first by name
in ascending order and then by age
in ascending order within each name group.
Comments
Post a Comment