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 ): MThis 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
pairList1containing pairs of characters and integers. - We convert
pairList1to 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
map1to 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
pairList2containing pairs of strings and integers. - We create a mutable map named
map2. - We populate
map2with key-value pairs frompairList2using thetoMap()function. - Finally, we print
map2to 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
pairList3containing pairs of strings and integers. - We create a mutable map named
map3. - We populate
map3with key-value pairs frompairList3using thetoMap()function. - Finally, we print
map3to 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.