Sorting list based on another list's order
An efficient solution is to first create the mapping from the ID in the ids
(your desired IDs order) to the index in that list:
val orderById = ids.withIndex().associate { it.value to it.index }
And then sort your list of people
by the order of their id
in this mapping:
val sortedPeople = people.sortedBy { orderById[it.id] }
Note: if a person has an ID that is not present in the ids
, they will be placed first in the list. To place them last, you can use a nullsLast
comparator:
val sortedPeople = people.sortedWith(compareBy(nullsLast<String>) { orderById[it.id] })