To get the size (number of key-value pairs) of a map in Kotlin, you can use the size property. This property returns the number of elements in the map.
We can get the size of a map in Kotlin using the size property, which provides the number of key-value pairs in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.size
property to get the number of key-value pairs in the map.mapSize
.println
function to verify the number of key-value pairs in the map.fun main() {
// Declare and initialize a map
val myMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Get the size of the map
val mapSize = myMap.size
// Print the size
println("Size of the map: $mapSize")
}
Size of the map: 3
We can also get the size of an empty map in Kotlin using the size property, which returns 0 when the map is empty.
For example,
emptyMap
with string keys and integer values.size
property to get the number of key-value pairs in the empty map.emptyMapSize
.println
function to verify that the map is empty.fun main() {
// Declare an empty map
val emptyMap = mapOf<String, Int>()
// Get the size of the empty map
val emptyMapSize = emptyMap.size
// Print the size
println("Size of the empty map: $emptyMapSize")
}
Size of the empty map: 0
We can get the size of a map in Kotlin after adding elements using the size property, which provides the updated number of key-value pairs in the map.
For example,
dynamicMap
with string keys and integer values.put
method.size
property to get the number of key-value pairs in the map after adding elements.dynamicMapSize
.println
function to verify the updated number of key-value pairs in the map.fun main() {
// Declare an empty mutable map
val dynamicMap = mutableMapOf<String, Int>()
// Add elements to the map
dynamicMap["one"] = 1
dynamicMap["two"] = 2
dynamicMap["three"] = 3
// Get the size of the map after adding elements
val dynamicMapSize = dynamicMap.size
// Print the size
println("Size of the map after adding elements: $dynamicMapSize")
}
Size of the map after adding elements: 3
In this tutorial, we learned How to Get the Size (Number of Key-Value Pairs) of a Map in Kotlin language with well detailed examples.