What is the HashMap.containsKey method in Dart?

A Hash-table based implementation of mapA Map contains a list of key-value pairs as an element.. Read more about what a HashMap is here.

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 value
HashMap map = new HashMap<String, int>();
// add two entries to the map
map["one"] = 1;
map["two"] = 2;
print('The map is $map');
// Using the "containsKey" mehod to check if the map has a specific key
print('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 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.

Free Resources