How do I order ids based on some logical ranking, ...
# getting-started
s
How do I order ids based on some logical ranking, let's say I have IDs of 1,2,3,4,5. But I want to rank them in order of 3,4,2,1,5. Here Id 3 is most important category and should be ranked first. Ids are Int
k
Copy code
val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))
Provide your own custom
Comparator
👍 1
j
probably your own class Id extending comparator is a good idea here
j
I don't get the logic for the ordering, do you just want 3 to be first? Or you have a whole arbitrary order for every possible ID, and you want to order lists of IDs according to this "master list"?
3
p
Yeah, the general answer is 'use a custom comparator', but this is an underspecified question (or maybe an XY problem)
👍 1
s
@Joffrey Yes, Master list would be right way to think of it. Not just 3, that was just an example. Master list is list of Ints. Ids are ints.
j
In this case I would probably build a map from this "master list", from each ID to its position in the order, and use that to write a custom sort function like this:
Copy code
/** 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]
}
🤔 1
s
Thanks. How can I pass this to sortedWith(compareBy ( { sorting logic 1 }, { sorting logic 2 }, { /*HERE - ranking logic*/ }) )