Kotlin List mapTo()
Syntax & Examples
Syntax of List.mapTo()
The syntax of List.mapTo() extension function is:
fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo( destination: C, transform: (T) -> R ): C
This mapTo() extension function of List applies the given transform function to each element of the original collection and appends the results to the given destination.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the integers1, 2, 3
. - We create an empty mutable list named
destination
to store the transformed elements. - We then apply the
mapTo
function tolist1
, which takes a lambda with one parameter:it
. - Within the lambda, we double each element.
- The
mapTo
function appends the transformed elements to thedestination
list. - The resulting list, containing doubled values of elements from
list1
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3);
val destination = mutableListOf<Int>();
val result = list1.mapTo(destination) { it * 2 }
print(result);
}
Output
[2, 4, 6]
2 Example
In this example,
- We create a list named
list1
containing the characters'a', 'b', 'c'
. - We create an empty mutable list named
destination
to store the transformed elements. - We then apply the
mapTo
function tolist1
, which takes a lambda with one parameter:it
. - Within the lambda, we convert each character to uppercase.
- The
mapTo
function appends the transformed elements to thedestination
list. - The resulting list, containing uppercase versions of characters from
list1
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c");
val destination = mutableListOf<String>();
val result = list1.mapTo(destination) { it.toUpperCase() }
print(result);
}
Output
[A, B, C]
3 Example
In this example,
- We create a list named
list1
containing the strings'apple', 'banana', 'cherry'
. - We create an empty mutable list named
destination
to store the transformed elements. - We then apply the
mapTo
function tolist1
, which takes a lambda with one parameter:it
. - Within the lambda, we get the length of each string.
- The
mapTo
function appends the transformed elements to thedestination
list. - The resulting list, containing the lengths of strings from
list1
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry");
val destination = mutableListOf<Int>();
val result = list1.mapTo(destination) { it.length }
print(result);
}
Output
[5, 6, 6]
Summary
In this Kotlin tutorial, we learned about mapTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.