Kotlin Set toSet()
Syntax & Examples


toSet() extension function

The toSet() extension function in Kotlin returns a Set containing all elements of the collection.


Syntax of toSet()

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

fun <T> Iterable<T>.toSet(): Set<T>

This toSet() extension function of Set returns a Set of all elements.

Return Type

Set.toSet() returns value of type Set.



✐ Examples

1 Converting a list of integers to a set

Using toSet() to convert a list of integers to a set.

For example,

  1. Create a list of integers.
  2. Use toSet() to convert the list to a set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val intList = listOf(1, 2, 3, 3, 4, 5)
    val intSet = intList.toSet()
    println(intSet)
}

Output

[1, 2, 3, 4, 5]

2 Converting a list of strings to a set

Using toSet() to convert a list of strings to a set.

For example,

  1. Create a list of strings.
  2. Use toSet() to convert the list to a set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val stringList = listOf("one", "two", "three", "two")
    val stringSet = stringList.toSet()
    println(stringSet)
}

Output

[one, two, three]

3 Converting a list of custom objects to a set

Using toSet() to convert a list of custom objects to a set.

For example,

  1. Create a data class.
  2. Create a list of custom objects.
  3. Use toSet() to convert the list to a set.
  4. Print the resulting set.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val peopleList = listOf(Person("Alice", 30), Person("Bob", 25), Person("Alice", 30))
    val peopleSet = peopleList.toSet()
    println(peopleSet)
}

Output

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

Summary

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