Kotlin Tutorials

Kotlin Set sortedWith()
Syntax & Examples

Set.sortedWith() extension function

The sortedWith() extension function in Kotlin returns a list of all elements sorted according to the specified comparator.


Syntax of Set.sortedWith()

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.

Parameters

ParameterOptional/RequiredDescription
comparatorrequiredThe comparator used to compare elements.

Return Type

Set.sortedWith() returns value of type List.



✐ Examples

1 Sorting a set of integers with a custom comparator

Using sortedWith() to sort a set of integers with a custom comparator that sorts in descending order.

For example,

  1. Create a set of integers.
  2. Create a custom comparator that sorts integers in descending order.
  3. Use sortedWith() with the custom comparator.
  4. Print the resulting sorted list.

Kotlin Program

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

Output

[5, 4, 3, 2, 1]

2 Sorting a set of strings with a custom comparator

Using sortedWith() to sort a set of strings with a custom comparator that sorts by the last character of each string.

For example,

  1. Create a set of strings.
  2. Create a custom comparator that sorts strings by the last character.
  3. Use sortedWith() with the custom comparator.
  4. Print the resulting sorted list.

Kotlin Program

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

Output

[three, one, two]

3 Sorting a set of custom objects with a custom comparator

Using sortedWith() to sort a set of custom objects with a custom comparator that sorts by age.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Create a custom comparator that sorts by age.
  4. Use sortedWith() with the custom comparator.
  5. 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 comparator = Comparator<Person> { a, b -> a.age.compareTo(b.age) }
    val sortedPeople = people.sortedWith(comparator)
    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 sortedWith() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.