Sorting a collection by multiple fields in Kotlin
Hello everyone! I just started learning Kotlin and encountered a task of sorting a list of objects by multiple fields. For example, I have a Person class:
```kotlin
data class Person(val name: String, val age: Int, val height: Double)
```
And a list of people:
```kotlin
val people = listOf(
Person("Alice", 25, 165.0),
Person("Bob", 30, 180.0),
Person("Charlie", 25, 170.0),
Person("Alice", 30, 160.0)
)
```
I need to sort this list first by name (ascending), then by age (ascending), and then by height (descending). In Java I would use Comparator with a thenComparing chain. In Kotlin there is a sortedWith function, but I don't understand how to apply it correctly for multiple fields. I tried writing something like:
```kotlin
val sorted = people.s
No answers yet.
Log in to leave an answer
Blogs