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.
Case-insensitive Sorting By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters.
Sorting on the basis of the ASCII values differentiates the uppercase letters from the lowercase letters, and results in a case-sensitive order.
Therefore, case sensitive order means, capital and small letters will be considered irrespective of case. The output would be − E, g, H, K, P, t, W. The following is our array − String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" }; Convert the above array to a List − List<String>list = Arrays.asList(arr);
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.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.name }))
Sort Ascending - case insensitive:
myList.sortedBy { it.name?.toLowerCase() }
Sort Descending - case insensitive:
myList.sortedByDescending { it.name?.toLowerCase() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With