What is the HashMap.containsKey method in Dart?
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.
Syntax
bool containsKey(Object? key)
Parameter
This method takes the value of the key that needs to be checked for in the Map, as an argument.
Return value
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.
Code
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")}');}
Code explanation
In the code given above:
-
In line 1, we import the
collectionlibrary. -
In line 4, we create a new
HashMapobject with the namemap. -
In lines 7 and 8, we add two new entries to the
map. -
In line 12, we use the
containsKeymethod with “one” as an argument. This checks if the map has an entry with the keyone. In our case, there is an entry with the keyone, so the method returnsTrue. -
In line 13, we use the
containsKeymethod with “three” as an argument. This checks if the map has an entry with the keythree. In our case, there is no entry with the keythreein the map, so the method returnsFalse.