我想根据学生的受欢迎程度对学生列表进行排序(此列表始终按他们的分数排序),然后按字母顺序对不在该列表中的学生进行排序
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)
)
Run Code Online (Sandbox Code Playgroud)
[
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")
]
Run Code Online (Sandbox Code Playgroud)
如果有人知道这样做的有效方法,我将不胜感激
将排名作为列表并不是最理想的,因为要查找内容,您每次都需要浏览列表,如果您有很多排名,则速度会很慢。如果你确实有很多,我建议先把它们作为地图。您可以使用 轻松地从列表中完成此操作associate。
然后,您可以创建一个自定义比较器来按受欢迎程度进行比较,然后按名称进行比较,并将其用于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)
Run Code Online (Sandbox Code Playgroud)
您可以在这里看到结果: 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)
Run Code Online (Sandbox Code Playgroud)