I want to sort the ArrayList
by the age and then, if two people have the same age, by their name in alphabetical order.
Here's my code:
import java.util.*
import kotlin.collections.ArrayList
fun main(args:Array<String>){
var listName=ArrayList<person>()
listName.add(person("ahmed",25))
listName.add(person("Fethi",28))
listName.add(person("abdou",28))
Collections.sort(listName)
for(person in listName){
println("the name:${person.name} and the age is:${person.age}")
}
}
class person(
var name:String?=null,
var age:Int=null
):Comparable<person> {
override fun compareTo(other: person): Int {
return this.age!!-other.age!!
}
}
I expect the following output:
According to the example you provided, you want to sort the collection by age (ascending) and then by name in alphabetical order.
You can easily achieve that in Kotlin by using the sortedWith
extension function (that accepts a Comparator
):
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(
Person("Ahmed", 25),
Person("Fethi", 28),
Person("Abdou", 28)
)
val comparator = Comparator.comparingInt(Person::age).thenComparing(Person::name)
val sortedPeople = people.sortedWith(comparator)
println(sortedPeople)
}
Result:
[Person(name=Ahmed, age=25), Person(name=Abdou, age=28), Person(name=Fethi, age=28)]
Note: I slightly changed the Person
class and the main
method to follow Kotlin conventions and best practices around mutable variables and nullable types
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.