The sortedBy() extension function in Kotlin returns a list of all elements sorted according to the natural sort order of the value returned by the specified selector function.
The syntax of Set.sortedBy() extension function is:
fun <T, R : Comparable<R>> Set<T>.sortedBy(selector: (T) -> R?): List<T>
This sortedBy() extension function of Set returns a list of all elements sorted according to the natural sort order of the value returned by specified selector function.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be compared. |
Set.sortedBy() returns value of type List
.
Using sortedBy() to sort a set of integers by their natural order.
For example,
fun main() {
val numbers = setOf(5, 2, 3, 1, 4)
val sortedNumbers = numbers.sortedBy { it }
println(sortedNumbers)
}
[1, 2, 3, 4, 5]
Using sortedBy() to sort a set of strings by their length.
For example,
fun main() {
val strings = setOf("one", "three", "two")
val sortedStrings = strings.sortedBy { it.length }
println(sortedStrings)
}
[one, two, three]
Using sortedBy() to sort a set of custom objects by a specific property.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val sortedPeople = people.sortedBy { it.age }
println(sortedPeople)
}
[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about sortedBy() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.