Sort a List of strings in Kotlin
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.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf("ABC", "CD", "BAB", "BBA", "AAB") list.sort() println(list) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class User(val id: String, val age: Int) { override fun toString(): String { return "{$id, $age}" } } fun main() { val list = mutableListOf(User("ABC", 10), User("CD", 20), User( "BAB", 30), User( "BBA", 40), User( "AAB", 50)) list.sortedBy { it.id } println(list) } |
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.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf("Abc", "CD", "bAB", "BBA", "aAb") list.sortWith(String.CASE_INSENSITIVE_ORDER) println(list) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
data class User(val id: String, val age: Int) { override fun toString(): String { return "{$id, $age}" } } fun main() { val list = mutableListOf( User("Abc", 10), User("CD", 20), User( "bAB", 30), User( "BBA", 40), User( "aAb", 50)) list.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.id })) println(list) } |
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.
|
1 2 3 4 5 6 |
fun main() { val list = mutableListOf("ABC", "CD", "BAB", "BBA", "AAB") val sorted_list = list.sortedWith(naturalOrder()) println(sorted_list) } |
Output:
[AAB, ABC, BAB, BBA, CD]
That’s all about sorting a list of strings in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)