A Hash-table based implementation of
. Read more about what a HashMap is here. map A Map contains a list of key-value pairs as an element.
The containsKey
method can be used to check if the Map contains a specific key.
bool containsKey(Object? key)
This method takes the value of the key
that needs to be checked for in the Map, as an argument.
This method returns True
if the passed key is equal to any of the keys in the map.
Note: The key equality is checked based on the equality used by the Map.
The code given below shows us how to check if the HashMap
contains an entry for the specified key:
import 'dart:collection';void main() {//create a new hashmap which can have string type as key, and int type as valueHashMap map = new HashMap<String, int>();// add two entries to the mapmap["one"] = 1;map["two"] = 2;print('The map is $map');// Using the "containsKey" mehod to check if the map has a specific keyprint('map.containsKey("one") is ${map.containsKey("one")}');print('map.containsKey("three") is ${map.containsKey("three")}');}
In the code given above:
In line 1, we import the collection
library.
In line 4, we create a new HashMap
object with the name map
.
In lines 7 and 8, we add two new entries to the map
.
In line 12, we use the containsKey
method with “one” as an argument. This checks if the map has an entry with the key one
. In our case, there is an entry with the key one
, so the method returns True
.
In line 13, we use the containsKey
method with “three” as an argument. This checks if the map has an entry with the key three
. In our case, there is no entry with the key three
in the map, so the method returns False
.