Kotlin Set toCollection()
Syntax & Examples


Set.toCollection() extension function

The toCollection() extension function in Kotlin appends all elements to the given destination collection.


Syntax of Set.toCollection()

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

fun <T, C : MutableCollection<in T>> Set<T>.toCollection(destination: C): C

This toCollection() extension function of Set appends all elements to the given destination collection.

Parameters

ParameterOptional/RequiredDescription
destinationrequiredThe collection to which elements will be appended.

Return Type

Set.toCollection() returns value of type C.



✐ Examples

1 Appending elements of a set to a mutable list

Using toCollection() to append elements of a set to a mutable list.

For example,

  1. Create a set of integers.
  2. Create a mutable list of integers.
  3. Use toCollection() to append the elements of the set to the mutable list.
  4. Print the resulting list.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3)
    val destination = mutableListOf<Int>()
    numbers.toCollection(destination)
    println(destination)
}

Output

[1, 2, 3]

2 Appending elements of a set of strings to a mutable set

Using toCollection() to append elements of a set of strings to a mutable set.

For example,

  1. Create a set of strings.
  2. Create a mutable set of strings.
  3. Use toCollection() to append the elements of the set to the mutable set.
  4. Print the resulting set.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val destination = mutableSetOf<String>()
    strings.toCollection(destination)
    println(destination)
}

Output

[one, two, three]

3 Appending elements of a set of custom objects to a mutable list

Using toCollection() to append elements of a set of custom objects to a mutable list.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Create a mutable list of custom objects.
  4. Use toCollection() to append the elements of the set to the mutable list.
  5. 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))
    val destination = mutableListOf<Person>()
    people.toCollection(destination)
    println(destination)
}

Output

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

Summary

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