To create a map with initial key-value pairs in Kotlin, you can use the mapOf function. This creates a new map object with predefined key-value pairs.
We can create a map in Kotlin with initial key-value pairs using the mapOf function, which initializes a map with predefined key-value pairs.
For example,
myMap
. This variable will hold our map with initial key-value pairs.mapOf
function to create a new map object. In Kotlin, the mapOf
function allows us to specify key-value pairs directly within the function call.myMap
variable. In this example, the map has string keys and integer values.fun main() {
// Declare a map with initial key-value pairs
val myMap: Map<String, Int> = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Operations on the map
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3
We can create a map in Kotlin with initial key-value pairs of different types using the mapOf function.
For example,
studentGrades
. This variable will hold our map with initial key-value pairs where keys are strings (student names) and values are characters (grades).mapOf
function to create a new map object. In Kotlin, the mapOf
function allows us to specify key-value pairs directly within the function call.studentGrades
variable. In this example, the map has string keys and char values representing grades.fun main() {
// Declare a map with initial key-value pairs
val studentGrades: Map<String, Char> = mapOf(
"Alice" to 'A',
"Bob" to 'B',
"Charlie" to 'C'
)
// Operations on the map
for ((key, value) in studentGrades) {
println("$key: $value")
}
}
Alice: A Bob: B Charlie: C
We can create a map in Kotlin with initial key-value pairs where keys are integers and values are floats using the mapOf function.
For example,
productPrices
. This variable will hold our map with initial key-value pairs where keys are integers (product IDs) and values are floats (prices).mapOf
function to create a new map object. In Kotlin, the mapOf
function allows us to specify key-value pairs directly within the function call.productPrices
variable. In this example, the map has integer keys and float values.fun main() {
// Declare a map with initial key-value pairs
val productPrices: Map<Int, Float> = mapOf(
101 to 29.99f,
102 to 39.99f,
103 to 49.99f
)
// Operations on the map
for ((key, value) in productPrices) {
println("Product $key: $value")
}
}
Product 101: 29.99 Product 102: 39.99 Product 103: 49.99
In this tutorial, we learned How to create a Map with Initial Key-Value Pairs in Kotlin language with well detailed examples.