kotlin

How to sort objects list in case insensitive order?


Let's say I have a list of Strings in Kotlin: stringList: MutableList<String>

Then it is is easy to sort such list in case insensitive order by doing this:

stringList.sortWith(String.CASE_INSENSITIVE_ORDER)

But how would I sort a list of objects in case insensitive order? For example: places: MutableList<Place>

Where Place is a simple class with 2 fields - name: String and id: Int, and I would like to sort these Places by the name field.

I tried to do something like this: places.sortedWith(compareBy { it.name }) but this solution doesn't take letter case into account.


Solution

  • It looks like compareBy might be able to take a Comparator as an argument, see the documentation here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html

    Try:

    places.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.name }))
    

    or

    places.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, Place::name))
    

    to sort the list in place, or you can assign it to a new variable using

    val newList = places.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.name }))