Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashmap
kotlin
containskey
communitycreator

How to check if LinkedHashMap has a mapping for a key in Kotlin

Programming Bytes

The containsKey() method checks if the LinkedHashMap contains an entry for a specific key passed as an argument.

Syntax

fun containsKey(key: K): Boolean
Syntax of containsKey method

Argument

This method takes the key to be checked for presence as an argument.

Return value

This method returns true if the passed key has a mapping in the LinkedHashMap. Otherwise, it returns false.

Code

The code below demonstrates how to check if the LinkedHashMap contains an entry for a specific key:

fun main() {
  //create a new LinkedHashMap which can have integer type as key, and string type as value
  val map: LinkedHashMap<Int, String> = linkedMapOf()
  map.put(1, "one")
  map.put(2, "two")
  println("The map is : $map")
  print("Checking if the map has key '1' : ")
  var hasKey: Boolean = map.containsKey(1)
  println(hasKey)

  hasKey = map.containsKey(3)
  print("Checking if the map has key '3' : ")
  println(hasKey)

}

Explanation

  • Line 3: We create a new LinkedHashMap object named map. We used the linkedMapOf method to create an empty LinkedHashMap.
  • Lines 4 and 5: We add two new entries {1=one, 2=two} to the map using the put() method.
  • Line 8: We used the containsKey() method with 1 as an argument. This checks if the map has an entry for the key, 1. There is an entry for 1, so true is returned in our case.
  • Line 11: We use the containsKey() method with 3 as an argument. This checks if the map has an entry for the key, 3. In our case, there is no entry for 3 in the map. Hence, false is returned.

RELATED TAGS

linkedhashmap
kotlin
containskey
communitycreator
RELATED COURSES

View all Courses

Keep Exploring