Kotlin Tutorials

Kotlin Set reversed()
Syntax & Examples

Set.reversed() extension function

The reversed() extension function in Kotlin returns a list with elements in reversed order.


Syntax of Set.reversed()

The syntax of Set.reversed() extension function is:

fun <T> Set<T>.reversed(): List<T>

This reversed() extension function of Set returns a list with elements in reversed order.

Return Type

Set.reversed() returns value of type List.



✐ Examples

1 Reversing a set of integers

Using reversed() to reverse the order of elements in a set of integers.

For example,

  1. Create a set of integers.
  2. Use reversed() to reverse the order of elements in the set.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val reversedNumbers = numbers.reversed()
    println(reversedNumbers)
}

Output

[5, 4, 3, 2, 1]

2 Reversing a set of strings

Using reversed() to reverse the order of elements in a set of strings.

For example,

  1. Create a set of strings.
  2. Use reversed() to reverse the order of elements in the set.
  3. Print the resulting list.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val reversedStrings = strings.reversed()
    println(reversedStrings)
}

Output

[three, two, one]

3 Reversing a set of custom objects

Using reversed() to reverse the order of elements in a set of custom objects.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use reversed() to reverse the order of elements in the set.
  4. Print the resulting 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 reversedPeople = people.reversed()
    println(reversedPeople)
}

Output

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

Summary

In this Kotlin tutorial, we learned about reversed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.