Skip to main content

How to get the size of a HashMap in Kotlin

How to get the size of a HashMap in Kotlin.

Here's a step-by-step tutorial on how to get the size of a HashMap in Kotlin.

Step 1: Create a HashMap

First, you need to create a HashMap in Kotlin. You can do this by using the HashMap class and providing the appropriate type for the key and value. For example, let's create a HashMap with String as the key type and Int as the value type:

val hashMap = HashMap<String, Int>()

Step 2: Add elements to the HashMap

Next, you can add elements to the HashMap using the put method. This method takes two parameters: the key and the value. Let's add a few elements to our HashMap:

hashMap.put("A", 1)
hashMap.put("B", 2)
hashMap.put("C", 3)

Step 3: Get the size of the HashMap

To get the size of the HashMap, you can use the size property. It returns the number of key-value pairs in the HashMap. Here's how you can get the size of the HashMap we created:

val size = hashMap.size
println("Size of the HashMap is: $size")

Step 4: Print the size of the HashMap

Finally, you can print the size of the HashMap to see the result. In our case, it will output:

Size of the HashMap is: 3

Step 5: Alternative way - using the size() method

Alternatively, you can also use the size() method to get the size of the HashMap. It works the same way as the size property. Here's how you can use it:

val size = hashMap.size()
println("Size of the HashMap is: $size")

That's it! You have successfully learned how to get the size of a HashMap in Kotlin. You can use either the size property or the size() method to achieve the same result.