The toSortedSet() extension function in Kotlin returns a new SortedSet containing all elements of the collection, sorted according to the specified comparator.
The syntax of Set.toSortedSet() extension function is:
fun <T> Iterable<T>.toSortedSet(comparator: Comparator<in T>): SortedSet<T>
This toSortedSet() extension function of Set returns a new SortedSet of all elements.
Parameter | Optional/Required | Description |
---|---|---|
comparator | required | The comparator used to determine the order of the elements in the sorted set. |
Set.toSortedSet() returns value of type SortedSet
.
Using toSortedSet() to convert a set of integers to a SortedSet in descending order.
For example,
fun main() {
val intSet = setOf(1, 2, 3, 4, 5)
val sortedSet = intSet.toSortedSet(compareByDescending { it })
println(sortedSet)
}
[5, 4, 3, 2, 1]
Using toSortedSet() to convert a set of strings to a SortedSet by string length.
For example,
fun main() {
val stringSet = setOf("one", "two", "three", "four")
val sortedSet = stringSet.toSortedSet(compareBy { it.length })
println(sortedSet)
}
[one, two, four, three]
Using toSortedSet() to convert a set of custom objects to a SortedSet by a custom property.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val peopleSet = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val sortedSet = peopleSet.toSortedSet(compareBy { it.age })
println(sortedSet)
}
[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about toSortedSet() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.