Kotlin Array.toMap()

Kotlin Array.toMap() Tutorial

The Array.toMap() function in Kotlin is used to convert an array of key-value pairs into a map. It creates a new map where each element of the array is treated as a key-value pair.

Array.toMap() function is particularly useful when you have data represented as pairs and want to work with it as a map in your Kotlin code.

This tutorial will explore the syntax of the Array.toMap() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.toMap() function is as follows:

fun <K, V> Array<out Pair<K, V>>.toMap(): Map<K, V>

The Array.toMap() function returns a Map object.

Examples for Array.toMap() function

1. Convert given Array of key-values to a Map

In this example, we’ll take an Array of Pairs in keyValueArray, and use toMap() on this Array to convert it into a map.

Kotlin Program

fun main() {
    val keyValueArray = arrayOf(
        Pair("apple", 5),
        Pair("banana", 3),
        Pair("orange", 8),
        Pair("grape", 12)
    )

    // Using toMap() to convert the array of key-value pairs to a map
    val resultMap = keyValueArray.toMap()

    // Printing the original array and the resulting map
    println("Input Array:\n${keyValueArray.contentToString()}\n")
    println("Output Map:\n$resultMap")
}

Output

Input Array:
[(apple, 5), (banana, 3), (orange, 8), (grape, 12)]

Output Map:
{apple=5, banana=3, orange=8, grape=12}

Summary

In this tutorial, we’ve covered the Array.toMap() function in Kotlin, its syntax, and how to use it to convert an array of key-value pairs into a map.