Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 11 / 68

Sorting a List

In this lesson you will learn to sort a list with sort in Kotlin, a basic operation you will use constantly in practice. This is for anyone searching for "Kotlin list sort how to use".

.sort() reorders a list in place. Kotlin lists come with a great many handy methods.

The sample code creates a mutable list with mutableListOf(5, 3, 8, 1, 9) and sorts it into ascending order with nums.sort(). Notice that without mutableListOf() you could not call sort() at all.

A common stumbling block for beginners is the difference between sort() and sorted(). sort() rewrites the original list while sorted() returns a new one, and missing that leads to behaviour you did not intend.

In real-world development, sortedBy lets you order by your own comparison rule, giving you flexible sorting to suit the purpose.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)