Search code examples
listsortingkotlincomparison

Comparing strings in Kotlin by custom ordering defined in another list


I have a list of Accounts:

data class Account(
        val currency: String?
)

I need to sort the accounts by the currency, but not by the natural (alphabetical) ordering of the strings, which all the tutorials out there have already explained to the death, but by a custom ordering, defined preferably in a list, so I don't have to do some ugly "if-else" chain of some sort. For example, if I used the list

listOf("USD", "EUR", "RMB")

for the sorting, then accounts with currency "USD" would come first, those with "EUR second", and the ones with "RMB" last.


Solution

  • The sortedBy function will work:

    val sortOrder = listOf("USD", "EUR", "RMB")
    val accounts = listOf(Account("EUR"), Account("USD"), Account("RMB"))
    val sortedAccounts = accounts.sortedBy { sortOrder.indexOf(it.currency) }