To sort items of a Set in Kotlin, you can convert the Set to a List and use the sorted()
method.
In this example,
numberSet
with a set of integer values.numberSet
to a List using the toList()
method.sorted()
method of the List to sort the items in ascending order and store the result in sortedList
.sorted()
method returns a new List with all items sorted in ascending order.fun main() {
val numberSet = setOf(5, 3, 8, 1, 2);
val sortedList = numberSet.toList().sorted();
println("Sorted list: $sortedList");
}
Sorted list: [1, 2, 3, 5, 8]
In this example,
stringSet
with a set of string values.stringSet
to a List using the toList()
method.sorted()
method of the List to sort the items in alphabetical order and store the result in sortedList
.sorted()
method returns a new List with all items sorted in alphabetical order.fun main() {
val stringSet = setOf("banana", "apple", "cherry", "date");
val sortedList = stringSet.toList().sorted();
println("Sorted list: $sortedList");
}
Sorted list: [apple, banana, cherry, date]
In this tutorial, we learned How to Sort Items of a Set in Kotlin language with well detailed examples.