Kotlin Associate With New Items At End of List

Viewed 104

I am trying to use associate in kotlin to order one list according to another list. Here is my code:

    val a = listOf("G", "F", "E", "D", "C", "B", "A")
    val b = listOf("A", "G", "C")
    val order = b.withIndex().associate { it.value to it.index }
    println(a.sortedBy { order[it] })

this is outputting: [F, E, D, B, A, G, C] Notice how this code is placing the items that are not part of b at the beginning of the list. Is there a simple way to instead put the new items at the end of the list. So the output would be like this instead: [A, G, C, F, E, D, B]

1 Answers

If order[it] doesn't find the value in the dictionary, it returns null, which is sorted as less than any integers. You can use the alternative ?: operator to provide a value of your choice. If you want it to appear at the end, you can use Int.MAX_VALUE to return the largest possible integer.

>>> println(a.sortedBy { order[it] ?: Int.MAX_VALUE })
[A, G, C, F, E, D, B]
Related