Kotlin Set toSortedSet()
Syntax & Examples
toSortedSet() extension function
The toSortedSet() extension function in Kotlin returns a new SortedSet containing all elements of the collection, sorted according to the specified comparator.
Syntax of toSortedSet()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
comparator | required | The comparator used to determine the order of the elements in the sorted set. |
Return Type
Set.toSortedSet() returns value of type SortedSet
.
✐ Examples
1 Converting a set of integers to a SortedSet
Using toSortedSet() to convert a set of integers to a SortedSet in descending order.
For example,
- Create a set of integers.
- Use toSortedSet() with a comparator to sort the set in descending order.
- Print the resulting SortedSet.
Kotlin Program
fun main() {
val intSet = setOf(1, 2, 3, 4, 5)
val sortedSet = intSet.toSortedSet(compareByDescending { it })
println(sortedSet)
}
Output
[5, 4, 3, 2, 1]
2 Converting a set of strings to a SortedSet
Using toSortedSet() to convert a set of strings to a SortedSet by string length.
For example,
- Create a set of strings.
- Use toSortedSet() with a comparator to sort the set by string length.
- Print the resulting SortedSet.
Kotlin Program
fun main() {
val stringSet = setOf("one", "two", "three", "four")
val sortedSet = stringSet.toSortedSet(compareBy { it.length })
println(sortedSet)
}
Output
[one, two, four, three]
3 Converting a set of custom objects to a SortedSet
Using toSortedSet() to convert a set of custom objects to a SortedSet by a custom property.
For example,
- Create a data class.
- Create a set of custom objects.
- Use toSortedSet() with a comparator to sort the set by a custom property.
- Print the resulting SortedSet.
Kotlin Program
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)
}
Output
[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]
Summary
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.