To print a map in Kotlin, you can iterate over the map using the forEach method, a for loop, or the entries property to print each key-value pair.
We can print a map in Kotlin by iterating over the map using the forEach method and printing each key-value pair.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.forEach
method to iterate over each key-value pair in the map. The forEach
method takes a lambda expression that defines the operation to be performed on each element.println
function.fun main() {
// Declare and initialize a map
val myMap: Map<String, Int> = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Print the map using forEach method
myMap.forEach { (key, value) ->
println("$key: $value")
}
}
one: 1 two: 2 three: 3
We can print a map in Kotlin by iterating over the map using a for loop and printing each key-value pair.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.entry
represents each key-value pair in the map as a Map.Entry
object.println
function.fun main() {
// Declare and initialize a map
val myMap: Map<String, Int> = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Print the map using a for loop
for ((key, value) in myMap) {
println("$key: $value")
}
}
one: 1 two: 2 three: 3
We can print a map in Kotlin by iterating over the map using the entries property and printing each key-value pair.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.entries
property to get a set of the map's key-value pairs. Each entry in the set is a Map.Entry
object containing a key and a value.entry
represents each key-value pair in the map.println
function.fun main() {
// Declare and initialize a map
val myMap: Map<String, Int> = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Print the map using entries property
for (entry in myMap.entries) {
println("${entry.key}: ${entry.value}")
}
}
one: 1 two: 2 three: 3
In this tutorial, we learned How to Print a Map in Kotlin language with well detailed examples.