Skip to main content

How to check if a HashMap is empty in Kotlin

How to check if a HashMap is empty in Kotlin.

Here's a step-by-step tutorial on how to check if a HashMap is empty in Kotlin:

Step 1: Create a HashMap

First, you need to create a HashMap in Kotlin. A HashMap is a collection that stores key-value pairs. You can create a HashMap using the HashMap class constructor or by using the hashMapOf function.

val hashMap = HashMap<String, Int>()

Step 2: Check if the HashMap is empty using the isEmpty() function

To check if a HashMap is empty, you can use the isEmpty() function. This function returns true if the HashMap does not contain any key-value pairs, and false otherwise.

if (hashMap.isEmpty()) {
println("HashMap is empty")
} else {
println("HashMap is not empty")
}

Step 3: Use the size property as an alternative

Alternatively, you can use the size property of the HashMap to check if it is empty. The size property returns the number of key-value pairs in the HashMap. If the size is 0, it means the HashMap is empty.

if (hashMap.size == 0) {
println("HashMap is empty")
} else {
println("HashMap is not empty")
}

Step 4: Check if the HashMap is null before performing the check

Before checking if a HashMap is empty, it is good practice to check if the HashMap itself is null. If the HashMap is null, you cannot call the isEmpty() function or access the size property without causing a NullPointerException.

if (hashMap == null) {
println("HashMap is null")
} else if (hashMap.isEmpty()) {
println("HashMap is empty")
} else {
println("HashMap is not empty")
}

Step 5: Check if the HashMap is empty using pattern matching

In Kotlin, you can use pattern matching with the when expression to check if a HashMap is empty. This approach can be useful if you want to perform different actions based on whether the HashMap is empty or not.

when {
hashMap.isEmpty() -> println("HashMap is empty")
else -> println("HashMap is not empty")
}

That's it! You now know how to check if a HashMap is empty in Kotlin using different approaches. Choose the method that suits your needs and implement it in your Kotlin projects.