How to sort a list ob objects based on a function in kotlin?

data class MyUser(
    val id: Int,
    val nameCode: String,

val myList : List<MyUser>()

fun getTitleFromCode(nameCode:String) {... return title}

How to sort myList alphabetically based on the Titles returned by getTitleFromCode for each MyUser?

>Solution :

You can sort a list using the natural sort order of some key function with sortedBy. In your case, your key function will need to get the nameCode field and then use that to call getTitleFromCode. So this should suffice:

myList.sortedBy { getTitleFromCode(it.length) }

Note that this will return a new list. If your initial list is mutable and you want to modify it in-place, you can use sortBy instead.

Leave a Reply