This article explores different ways to sort a list of strings in Kotlin.

1. Using sort() function

To in-place sort a list of strings in lexicographical order, use the sort() function. It takes a mutable list and results in a stable sort, i.e. the relative ordering of the equal elements remains preserved after sorting.

Download Code

Output:

[AAB, ABC, BAB, BBA, CD]

2. Using sortedBy() function

To sort a list of data classes by a string field, you can use the sortedBy() method.

Download Code

Output:

[{ABC, 10}, {CD, 20}, {BAB, 30}, {BBA, 40}, {AAB, 50}]

3. Using sortWith() function

Alternately, you can use the sortWith() function that takes a comparator to allow precise control over the sort order. For example, you can use the String.CASE_INSENSITIVE_ORDER comparator to compare two strings by ignoring their case.

Download Code

Output:

[aAb, Abc, bAB, BBA, CD]

 
To sort an object list in a case-insensitive manner, you can use sortWith() with the compareBy() function that uses String.CASE_INSENSITIVE_ORDER comparator.

Download Code

Output:

[{aAb, 50}, {Abc, 10}, {bAB, 30}, {BBA, 40}, {CD, 20}]

4. Using sortedWith() function

To create a sorted “copy” of the list without changing the original list, you can use the sortedWith() function that accepts a comparator.

Download Code

Output:

[AAB, ABC, BAB, BBA, CD]

That’s all about sorting a list of strings in Kotlin.