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 the toMap() 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(&quot;a&quot;, 1), Pair(&quot;b&quot;, 2), Pair(&quot;c&quot;, 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 from pairList2 using the toMap() function.
  • Finally, we print map2 to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val pairList2 = listOf(Pair(&quot;apple&quot;, 5), Pair(&quot;banana&quot;, 10), Pair(&quot;orange&quot;, 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 from pairList3 using the toMap() function.
  • Finally, we print map3 to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val pairList3 = listOf(Pair(&quot;John&quot;, 25), Pair(&quot;Emma&quot;, 30), Pair(&quot;Tom&quot;, 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.