What is a HashMap in Dart?

A HashMap is an implementation of a map based on a hashtable. A map is a collection of key-value pairs. Each value is associated with a key. A HashMap is an unordered collection of key-value pairs.

The keys of a HashMap must have Object.== and Object.hashCode implementations. These are used to create a hashcode for the key and store it in the hashtable.

Methods of HashMap

  • containsKey: This checks if there is a value associated with the given key.

  • clear: This clears all the entries on the map.

  • containsValue: This checks if there is a key associated with the given value.

  • remove: This removes the entry of the given key from the map.

  • putIfAbsent: This adds a new entry if no value is associated with the given key.

  • update: This updates the value of the provided key.

Example

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>();
// Print the map
print('\nThe map is $map');
// check if the map is empty
print('map.isEmpty ${map.isEmpty}');
// add two entries to the map
map["one"] = 1;
map["two"] = 2;
print('The map is $map');
// check if the map is empty
print('map.isEmpty ${map.isEmpty}');
//check if a key is present or not
print('map.containsKey("one") ${map.containsKey("one")}');
print('map.containsKey("three") ${map.containsKey("three")}');
//check if a value is present or not
print('map.containsValue(1) ${map.containsValue(1)}');
print('map.containsValue(3) ${map.containsValue(3)}');
}

Explanation

Line 4: We create a new HashMap object with the name map and the map can have string keys and integer type values.

Line 10: We use the isEmpty property to check if the map is empty. In our case, we get true because the map has no entries.

Lines 13 and 14: We add two new entries to the map. Now the map is {one: 1, two: 2}.

Line 17: We check if the map is empty or not. Now we get false because the map has two entries.

Lines 20 and 21: We use the containsKey method to check if the map has any value associated with the keys one and three. The map has value for key one so it returns true. For the key three, it returns false because there is no value associated with it.

Line 24: We use the containsValue method to check if the map has keys associated with the given value 1 . The key one is associated with the value 1 so true is returned.

Line 25: We check if the map has any key for the value 3 using the containsValue method. There is no key associated with the value 3 so false is returned.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved