Kotlin List toMap()
Syntax & Examples
Syntax of List.toMap()
There are 2 variations for the syntax of List.toMap() extension function. They are:
1.
fun <K, V> Iterable<Pair<K, V>>.toMap(): Map<K, V>
This extension function returns a new map containing all key-value pairs from the given collection of pairs.
2.
fun <K, V, M : MutableMap<in K, in V>> Iterable<Pair<K, V>>.toMap( destination: M ): M
This extension function populates and returns the destination mutable map with key-value pairs from the given collection of pairs.
✐ Examples
1 Example
In this example,
- We create a list of pairs named
pairList1
containing pairs of characters and integers. - We convert
pairList1
to a Map using thetoMap()
function. - The resulting Map contains all key-value pairs from the list, where characters are keys and integers are values.
- Finally, we print
map1
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val pairList1 = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3));
val map1 = pairList1.toMap();
println(map1);
}
Output
{a:1, b:2, c:3}
2 Example
In this example,
- We create a list of pairs named
pairList2
containing pairs of strings and integers. - We create a mutable map named
map2
. - We populate
map2
with key-value pairs frompairList2
using thetoMap()
function. - Finally, we print
map2
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val pairList2 = listOf(Pair("apple", 5), Pair("banana", 10), Pair("orange", 8));
val map2 = mutableMapOf<String, Int>();
pairList2.toMap(map2);
println(map2);
}
Output
{apple:5, banana:10, orange:8}
3 Example
In this example,
- We create a list of pairs named
pairList3
containing pairs of strings and integers. - We create a mutable map named
map3
. - We populate
map3
with key-value pairs frompairList3
using thetoMap()
function. - Finally, we print
map3
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val pairList3 = listOf(Pair("John", 25), Pair("Emma", 30), Pair("Tom", 28));
val map3 = mutableMapOf<String, Int>();
pairList3.toMap(map3);
println(map3);
}
Output
{John:25, Emma:30, Tom:28}
Summary
In this Kotlin tutorial, we learned about toMap() extension function of List: the syntax and few working examples with output and detailed explanation for each example.