Kotlin Set sortedBy()
Syntax & Examples


Set.sortedBy() extension function

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.


Syntax of Set.sortedBy()

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.

Parameters

ParameterOptional/RequiredDescription
selectorrequiredA function that takes an element and returns the value to be compared.

Return Type

Set.sortedBy() returns value of type List.



✐ Examples

1 Sorting a set of integers by their natural order

Using sortedBy() to sort a set of integers by their natural order.

For example,

  1. Create a set of integers.
  2. Use sortedBy() with a selector function that returns the integer itself.
  3. Print the resulting sorted list.

Kotlin Program

fun main() {
    val numbers = setOf(5, 2, 3, 1, 4)
    val sortedNumbers = numbers.sortedBy { it }
    println(sortedNumbers)
}

Output

[1, 2, 3, 4, 5]

2 Sorting a set of strings by their length

Using sortedBy() to sort a set of strings by their length.

For example,

  1. Create a set of strings.
  2. Use sortedBy() with a selector function that returns the length of each string.
  3. Print the resulting sorted list.

Kotlin Program

fun main() {
    val strings = setOf("one", "three", "two")
    val sortedStrings = strings.sortedBy { it.length }
    println(sortedStrings)
}

Output

[one, two, three]

3 Sorting a set of custom objects by a property

Using sortedBy() to sort a set of custom objects by a specific property.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use sortedBy() with a selector function that returns the value of the property to be compared.
  4. Print the resulting sorted list.

Kotlin Program

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)
}

Output

[Person(name=Bob, age=25), Person(name=Alice, age=30), Person(name=Charlie, age=35)]

Summary

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.