Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Efficient way of sorting list using another list and alphabetical order

Tags:

kotlin

I want to sort the students list based on their popularity (this list is always sorted by their points) and then sort the ones that aren't on that list in alphabetical order

  • The two lists look like:
students = listOf<Student>(
    Student(id = 3, name ="mike"),
    Student(id = 2,name ="mathew"),
    Student(id = 1,name ="john"),
    Student(id = 4,name ="alan")
)
val popularity = listOf<Ranking>(
    Ranking(id= 2, points = 30),
    Ranking(id= 3, points = 15)
)
  • The result I'm looking for would be:
[
 Student(id=2,name"mathew"), <- first, because of popularity
 Student(id=3,name="mike"),
 Student(id=4,name="alan"), <- starting here by alphabetical order
 Student(id=1,name="john")
]

If anyone knows about an efficient way of doing this I would kindly appreciate the help

like image 951
yuu Avatar asked Oct 18 '25 15:10

yuu


1 Answers

Having the rankings as a list is suboptimal, because to look things up you need to browse the list everytime, which is slow if you have many rankings. If you do have a lot of them, I would suggest to get them as a map first. You can do it easily from the list using associate.

Then you can create a custom comparator to compare by popularity and then by name, and use it in sortedWith:

val studentIdToPopularity = popularity.associate { it.id to it.points }

val studentComparator = compareByDescending<Student> { studentIdToPopularity[it.id] ?: 0 }.thenBy { it.name }
val sortedStudents = students.sortedWith(studentComparator)

You can see the result here: https://pl.kotl.in/a1GZ736jZ

Student(id=2, name=mathew)
Student(id=3, name=mike)
Student(id=4, name=alan)
Student(id=1, name=john)
like image 118
Joffrey Avatar answered Oct 20 '25 16:10

Joffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!