Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading