The sortedWith() extension function in Kotlin returns a list of all elements sorted according to the specified comparator.
The syntax of Set.sortedWith() extension function is:
fun <T> Set<T>.sortedWith(comparator: Comparator<in T>): List<T>
This sortedWith() extension function of Set returns a list of all elements sorted according to the specified comparator.
Parameter | Optional/Required | Description |
---|---|---|
comparator | required | The comparator used to compare elements. |
Set.sortedWith() returns value of type List
.
Using sortedWith() to sort a set of integers with a custom comparator that sorts in descending order.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val comparator = Comparator<Int> { a, b -> b.compareTo(a) }
val sortedNumbers = numbers.sortedWith(comparator)
println(sortedNumbers)
}
[5, 4, 3, 2, 1]
Using sortedWith() to sort a set of strings with a custom comparator that sorts by the last character of each string.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val comparator = Comparator<String> { a, b -> a.last().compareTo(b.last()) }
val sortedStrings = strings.sortedWith(comparator)
println(sortedStrings)
}
[three, one, two]
Using sortedWith() to sort a set of custom objects with a custom comparator that sorts by age.
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 comparator = Comparator<Person> { a, b -> a.age.compareTo(b.age) }
val sortedPeople = people.sortedWith(comparator)
println(sortedPeople)
}
[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about sortedWith() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.