Kotlin List sortedBy()
Syntax & Examples
Syntax of List.sortedBy()
The syntax of List.sortedBy() extension function is:
fun <T, R : Comparable<R>> Iterable<T>.sortedBy( selector: (T) -> R? ): List<T>
This sortedBy() extension function of List returns a list of all elements sorted according to natural sort order of the value returned by specified selector function.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the strings['banana', 'apple', 'cherry']
. - We call the
sortedBy
function onlist
, sorting the elements according to the length of each string. - The result, which is the sorted list
['apple', 'banana', 'cherry']
, is stored insortedList
. - Finally, we print the
sortedList
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("banana", "apple", "cherry");
val sortedList = list.sortedBy { it.length };
println(sortedList);
}
Output
[apple, banana, cherry]
2 Example
In this example,
- We define a data class
Person
withname
andage
properties. - We create a list named
people
containing instances ofPerson
. - We call the
sortedBy
function onpeople
, sorting the elements according to theage
property of eachPerson
object. - The result, which is the sorted list of
Person
objects by age, is stored insortedPeople
. - Finally, we print the
sortedPeople
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 29), Person("Bob", 35), Person("Charlie", 25));
val sortedPeople = people.sortedBy { it.age };
println(sortedPeople);
}
Output
[Person(name=Charlie, age=25), Person(name=Alice, age=29), Person(name=Bob, age=35)]
3 Example
In this example,
- We create a list named
list
containing the integers[3, 1, 4, 1, 5, 9, 2, 6]
. - We call the
sortedBy
function onlist
, sorting the elements in ascending order. - The result, which is the sorted list
[1, 1, 2, 3, 4, 5, 6, 9]
, is stored insortedList
. - Finally, we print the
sortedList
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(3, 1, 4, 1, 5, 9, 2, 6);
val sortedList = list.sortedBy { it };
println(sortedList);
}
Output
[1, 1, 2, 3, 4, 5, 6, 9]
Summary
In this Kotlin tutorial, we learned about sortedBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.