4

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

2
  • Well first you could create a map of the student ID to popularity value (instead of a list), so looking them up is O(1), and then define a custom comparator of Students that would use the popularity, or 0 if they are not in the map of popularities. Commented Nov 3, 2022 at 16:21
  • Do you mean code efficient or efficient in a matter of compute time? Commented Nov 3, 2022 at 16:32

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.