What is the LinkedHashMap.removeWhere method in Dart?

LinkedHashMap is an implementation of MapMap contains a list of key-value pairs as elements. that is based on a hash table. The LinkedHashMap maintains the insertion order of the entries. Read more about LinkedHashMap here.

The removeWhere method can be used to remove all the entries that satisfy the provided test condition.

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

Argument

This method takes a test function that can take two arguments — key and value — and returns a Boolean value. This method is invoked for each entry of the map.

The removeWhere will iterate the map and invoke the test function. If the test function returns true, then the current entry will be removed from the map.

Return value

This method doesn’t return any value.

Code

The code below demonstrates how to use the removeWhere method:

import 'dart:collection';
void main() {
//create a new LinkedHashMap which can have string type as key, and int type as value
LinkedHashMap map = new LinkedHashMap<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

In the code above,

  • In line 1, we import the collection library.

  • In line 4, we create a new LinkedHashMap object with the name map.

  • In lines 7-9, we add three new entries to the map. Now the map is {one: 1, two: 2, three: 3}.

  • In line 14, we use the removeWhere method with a test function as an argument. The test function will return true if the value is an odd number. In our case, the keys one and three have odd values, so these entries are removed from the map. After removing the odd value entries, the map will be {two:2}.

Free Resources