我有课:
class SportMan(
val name: String,
val points: Double,
}
并列出Sportman
对象的命名SportGuysList
。我想从具有前5个Sportman
对象的SportGuysList
创建新列表
发布于 2019-10-07 09:09:58
您可以首先按分数降序对列表进行排序,从列表中取出前5名球员,然后按原始列表中的索引对其进行排序:
val topByPoints = SportGuysList.sortedByDescending { it.points }.take(5)
val result = topByPoints.sortedBy { SportGuysList.indexOf(it) }
如果SportGuysList
很大,那么在排序期间搜索每个结果元素的索引可能需要很长时间,这样您就可以记住它旁边每个运动员的原始索引:
val result =
SportGuysList.withIndex() // now we have pairs of value-index
.sortedByDescending { it.value.points } // sort by points
.take(5) // top 5
.sortedBy { it.index } // sort back by index
.map { it.value } // take only value from an each indexed pair
去考特林游乐场试试:https://pl.kotl.in/kMkpkIdEH
https://stackoverflow.com/questions/58262354
复制相似问题