data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
)
val sortedPeople = people.sortedBy { it.age }
sortedPeople.forEach { println(it) }
}
- Define a data class
Person
with properties name
and age
. - Create a list of
Person
objects named people
with different names and ages. - Use the
sortedBy
function to sort the people
list based on the age
property in ascending order. - Store the sorted list in the variable
sortedPeople
. - Iterate over the sorted list using
forEach
and print each Person
object.