How to sort items of a list in Kotlin:
There are different ways in Kotlin
to sort the list items in ascending or descending orders. We can even sort a list of objects easily in Kotlin. In this tutorial, I will show you how to sort the items of a list in ascending and descending order with different examples.
1. How to sort a list of integers:
The Collection
class provides one method called sorted()
to sort a list. The syntax of the method is:
public fun > Iterable.sorted(): List
This method returns one new sorted list containing all the elements of the original list. It sorts the elements in the natural order. Let me show you how it works with an example:
fun main() {
val numsList = listOf(1,5,2,88,33,56,23,10)
val sortAsc = numsList.sorted()
println(sortAsc)
}
Download it on GitHub
If you run the above code, it will print the below output :
[1, 2, 5, 10, 23, 33, 56, 88]
As you can see that the sorted()
method sorts the list in natural order.
2. How to sort a list in descending order:
There is another method called sortedDescending
to sort the items of a list in descending order. The syntax of this method is:
public fun > Iterable.sortedDescending(): List
It will return a list of elements sorted in descending order according to their natural sort order. Let’s try this method with an example:
fun main() {
val numsList = listOf(1,5,2,88,33,56,23,10)
val sortAsc = numsList.sortedDescending()
println(sortAsc)
}
Download it on GitHub
If you run this program, it will print the below output:
[88, 56, 33, 23, 10, 5, 2, 1]
Similar to the sorted()
method, the sortedDescending()
method also returns a new list without modifying the original list.
How to reverse a list:
Similar to sorting, we can also reverse a list easily in Kotlin. The reversed()
method is used to reverse a list. The syntax of the reversed()
method is:
public fun Iterable.reversed(): List
It will reverse the list and return one new list with the elements in reversed order. Let’s try it with an example:
fun main() {
val numsList = listOf(1,5,2,88,33,56,23,10)
val sortAsc = numsList.reversed()
println(sortAsc)
}
If you run the above program, it will print the below output:
[10, 23, 56, 33, 88, 2, 5, 1]
3. Sort a list of custom objects by their property :
There are two different methods available to sort a list of objects in Kotlin
:
- To sort the list in ascending order, the
sortedBy()
method can be used. - Similarly, to sort the list in descending order, we can use the
sortedByDescending()
method.
We need to pass one selector function to these methods and based on this function, the list is sorted in ascending or descending order. These methods return a new list by sorting the elements according to the natural sort order of the return value of the provided function.
Let me show you how it works with an example:
fun main() {
val students = listOf(
Student("Alex", 54), Student("Rob", 34),
Student("Chandler", 11), Student("Bryan", 90)
)
println("Sorting by ascending : ")
val sortedStudents = students.sortedBy { student -> student.name }
sortedStudents.forEach { s -> println(s.name) }
println("Sorting by descending : ")
val dSortedStudents = sortedStudents.sortedByDescending { student -> student.name }
dSortedStudents.forEach { s -> println(s.name) }
}
class Student(val name: String, marks: Int)
Download it on GitHub
The parameter function is returning the name
of a Student
. It will sort the list according to the natural sort order of the name
.
If you run this program, it will print the below output:
Sorting by ascending :
Alex
Bryan
Chandler
Rob
Sorting by descending :
Rob
Chandler
Bryan
Alex
4. How to sort a list of String
:
We can use the sortedBy()
and sortedByDescending()
methods to sort a list of String
in any order we want. For example, the following example sorts the lists according to the natural sort order of the length of the strings:
fun main() {
val strList = listOf(
"a", "abcde", "abc", "ab", "abcd", "abcdef"
)
println("Ascending order: ")
val ascendingList = strList.sortedBy { it.length }
ascendingList.forEach { s -> println(s) }
println("Descending order: ")
val descendingList = strList.sortedByDescending { it.length }
descendingList.forEach { s -> println(s) }
}
Download it on GitHub
It will print:
Ascending order:
a
ab
abc
abcd
abcde
abcdef
Descending order:
abcdef
abcde
abcd
abc
ab
a
5. How to sort a list in any order with a comparator:
Instead of doing the ascending or descending sorting, we can also use a comparator and sort a list in any order.
The sortedWith()
method is used to sort a list using a comparator. The comparator is a function that is passed as an argument to the function. The following example shows how to use the sortedWith()
method with a list of objects:
fun main() {
val students = listOf(Student("Alex", 54), Student("Rob", 34),
Student("Chandler", 11), Student("Bryan", 90))
println("Sorting using a comparator : ")
val sortedStudents = students.sortedWith { student1, student2 -> student1.name.length - student2.name.length }
sortedStudents.forEach { s -> println(s.name) }
}
class Student(val name: String, marks: Int)
Download it on GitHub
The comparator will sort the list in increasing order according to the length of name
of each Student
object.
If you run the above program, it will print:
Sorting using a comparator :
Rob
Alex
Bryan
Chandler
You can create one custom Comparator
class and add any custom logic to the comparator.
Conclusion:
In this tutorial, we have learned how to sort a list in ascending/descending order, how to reverse a list, how to sort a list of custom objects, and how to sort a list using a custom comparator. If you want to add any more points to this post, please raise a pull request on GitHub.
You might also like:
- Kotlin development tutorial – Array in Kotlin
- Trim leading whitespace characters using trimMargin in Kotlin
- 6 different ways to sort an array in Kotlin
- How to use fold, foldIndexed, foldRight and foldRightIndexed in Kotlin
- Kotlin tutorial : Character in kotlin and functions of Character class
- Kotlin String template : Explanation with Examples