What is the HashMap.removeWhere method in Dart?

Overview

In Dart, the removeWhere method is used to remove all the entries that satisfy the provided test condition.

Note: HashMap.removeWhere is an implementation of MapMap contains a list of key-value pairs as an element. based on a hash table. Read more about HashMap here.

Syntax

void removeWhere( bool test(K key,V value) )

Parameter

This method takes a test function with two arguments, keys and values. It returns a boolean value. This method is invoked for each entry of the map.

The removeWhere method iterates the map and invokes the test function. If the test function returns true, the current entry is removed from the map.

Return value

This method doesn’t return any value.

Example

The code below demonstrates how to use the removeWhere method:

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 three entries to the map
map["one"] = 1;
map["two"] = 2;
map["three"] = 3;
print('The map is $map');
// Remove the entry with odd value
map.removeWhere((key, value){
return value % 2 != 0;
});
print('The map is $map');
}

Explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new HashMap object—map.

  • Lines 7–9: We add three new entries to the map. Due to this, the map now is {one: 1, two: 2, three: 3}.

  • Line 14: We use the removeWhere method with a test function as an argument. The test function returns true if the value is odd number. In our code, the key one and three have an odd value. Hence, those entries are removed from the map. After we remove the odd value entries, the map is {two:2}.

Free Resources