What is the LinkedHashMap.removeWhere method in Dart?
LinkedHashMap is an implementation of
that is based on a hash table. The LinkedHashMap maintains the insertion order of the entries. Read more about Map Map contains a list of key-value pairs as elements. LinkedHashMaphere.
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 valueLinkedHashMap map = new LinkedHashMap<String, int>();// add three entries to the mapmap["one"] = 1;map["two"] = 2;map["three"] = 3;print('The map is $map');// Remove the entry with odd valuemap.removeWhere((key, value){return value % 2 != 0;});print('The map is $map');}
Explanation
In the code above,
-
In line 1, we import the
collectionlibrary. -
In line 4, we create a new
LinkedHashMapobject with the namemap. -
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
removeWheremethod with atestfunction as an argument. Thetestfunction will returntrueif the value is an odd number. In our case, the keysoneandthreehave odd values, so these entries are removed from the map. After removing the odd value entries, the map will be{two:2}.