suhas
09/22/2021, 1:11 PMKirill Grouchnikov
09/22/2021, 1:22 PMval lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))
Comparator
Javier
09/22/2021, 1:34 PMJoffrey
09/22/2021, 1:37 PMPaul Griffith
09/22/2021, 2:16 PMsuhas
09/22/2021, 11:30 PMJoffrey
09/22/2021, 11:39 PM/** Defines the total order between all IDs */
private val order = listOf(3, 4, 2, 1, 5)
/** Maps each ID to its rank in the total order */
private val rankById = order.withIndex().associate { (index, id) -> id to index }
private fun List<Int>.sortedByCustomOrder() = sortedBy { rankById[it] }
fun main() {
println(listOf(1, 2, 3, 4, 5).sortedByCustomOrder()) // [3, 4, 2, 1, 5]
println(listOf(1, 2, 3).sortedByCustomOrder()) // [3, 2, 1]
println(listOf(2, 4, 5).sortedByCustomOrder()) // [4, 2, 5]
}
suhas
09/24/2021, 2:18 AM