#getting-started
Title
# getting-started
s

suhas

09/22/2021, 1:11 PM
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

Kirill Grouchnikov

09/22/2021, 1:22 PM
Copy code
``````val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))``````
``Comparator``
👍 1
j

Javier

09/22/2021, 1:34 PM
probably your own class Id extending comparator is a good idea here
j

Joffrey

09/22/2021, 1:37 PM
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

Paul Griffith

09/22/2021, 2:16 PM
Yeah, the general answer is 'use a custom comparator', but this is an underspecified question (or maybe an XY problem)
👍 1
s

suhas

09/22/2021, 11:30 PM
@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

Joffrey

09/22/2021, 11:39 PM
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

suhas

09/24/2021, 2:18 AM
Thanks. How can I pass this to sortedWith(compareBy ( { sorting logic 1 }, { sorting logic 2 }, { /*HERE - ranking logic*/ }) )
4 Views