Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort objects list in case insensitive order?

Tags:

kotlin

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.

like image 593
user2999943 Avatar asked Aug 28 '17 13:08

user2999943


People also ask

Which method is appropriate for case-insensitive sorting for a list?

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.

Is sorting not case sensitive?

Sorting on the basis of the ASCII values differentiates the uppercase letters from the lowercase letters, and results in a case-sensitive order.

What is case-insensitive order in Java?

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);


2 Answers

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 })) 
like image 112
Scott Newson Avatar answered Sep 28 '22 21:09

Scott Newson


Sort Ascending - case insensitive:

myList.sortedBy { it.name?.toLowerCase() } 

Sort Descending - case insensitive:

myList.sortedByDescending { it.name?.toLowerCase() } 
like image 29
Ivo Stoyanov Avatar answered Sep 28 '22 20:09

Ivo Stoyanov