Kotlin Map - Contains() Function



The Kotlin Map contains() function is used to check whether the specified element is present in the map. It returns true if the map element is equal to the argument of this function.

Here, are some use cases of the contains():

  • Checking key existence in a map.
  • Validating the user input.
  • Conditional execution based on presence.

Syntax

Following is the syntax of Kotlin Map contains() function −

Map.contains(element: T)

Parameters

This function accepts as a parameter a key that needs to be checked.

Return value

This function returns true if key is found in the map. Otherwise, return false.

Example 1: Checking Key Presence in a Map.

Let's see a basic example of the contains() function to verify if a key exists in a map.

fun main(args: Array<String>) {
   val userRoles = mapOf("Aman" to "Admin", "Vivek" to "User")
   //Check Key is present in map or not
   println(userRoles.contains("Aman"))
   println(userRoles.contains("User"))
}

Output

Following is the output −

true
true

Example 2: Validating User Input

The following example uses the contains() function to display the value of the specified key −

fun main(args: Array<String>) {
   val options = mapOf(1 to "Yes", 2 to "No", 3 to "Maybe")
   val userInput = 1
   if (options.contains(userInput)) {
      println("The value for the key $userInput is: ${options[userInput]}")
   } else {
      println("Invalid input")
   }
}

Output

Following is the output −

The value for the key 1 is: Yes

Example 3: Conditional Execution Based on Presence

This is another example of contains() function. It execute specific logic if a key exists in a map −

fun main(args: Array<String>) {
   val employee = mapOf<Int, String>(1 to "Aman", 2 to "Vivek", 3 to "Akash", 4 to "Rahul")
   val key = 1
   if (employee.contains(key)) {
      println("employee at ${key} is: ${employee[key]}")
   } else if(employee.contains(key+1)) {
      println("employee at ${key} is: $employee[key]")
   } else {
       println("Key does not exists!")
   }
}

Output

Following is the output −

You have a Potion to heal yourself.
kotlin_maps.htm
Advertisements