yuu
yuu

Reputation: 43

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

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

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)
)
[
 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

Upvotes: 4

Views: 210

Answers (1)

Joffrey
Joffrey

Reputation: 37680

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)

Upvotes: 6

Related Questions