Kotlin List toCollection()
Syntax & Examples
Syntax of List.toCollection()
The syntax of List.toCollection() extension function is:
fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection( destination: C ): C
This toCollection() extension function of List appends all elements to the given destination collection.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list1
with elements1, 2, 3, 4, 5
. - We create an empty mutable list named
list2
. - We use the
toCollection()
function onlist1
to append its elements tolist2
. - We then print the elements of
list2
usingjoinToString()
to display them separated by commas.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val list2 = mutableListOf<Int>()
list1.toCollection(list2)
println(list2.joinToString())
}
Output
1, 2, 3, 4, 5
2 Example
In this example,
- We create a list of characters named
list1
with elements'a', 'b', 'c'
. - We create an empty mutable list named
list2
. - We use the
toCollection()
function onlist1
to append its elements tolist2
. - We then print the elements of
list2
usingjoinToString()
to display them separated by commas.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf('a', 'b', 'c')
val list2 = mutableListOf<Char>()
list1.toCollection(list2)
println(list2.joinToString())
}
Output
a, b, c
3 Example
In this example,
- We create a list of strings named
list1
with elements"apple", "banana", "cherry"
. - We create an empty mutable list named
list2
. - We use the
toCollection()
function onlist1
to append its elements tolist2
. - We then print the elements of
list2
usingjoinToString()
to display them separated by commas.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry")
val list2 = mutableListOf<String>()
list1.toCollection(list2)
println(list2.joinToString())
}
Output
apple, banana, cherry
Summary
In this Kotlin tutorial, we learned about toCollection() extension function of List: the syntax and few working examples with output and detailed explanation for each example.