How to use removeWhere() in Dart
Overview
We can use the removeWhere() method to remove all the entries that satisfy the provided test condition.
Syntax
void removeWhere( bool test(K key,V value) )
Parameters
This method takes a test function that can take two arguments, key and value. It returns a Boolean value. This method is invoked for each entry of the SplayTreeMap.
The removeWhere method will iterate the SplayTreeMap and invoke the test function for each entry. 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.
Example
The code below demonstrates the use of the removeWhere() method to remove all entries of SplayTreeSet that match a provided test condition:
import 'dart:collection';void main() {//create a new SplayTreeMap which can have int key and string valuesSplayTreeMap map = new SplayTreeMap<int, String>((keya,keyb) => keyb.compareTo(keya));// add five entries to the mapmap[5] = "Five";map[4] = "Four";map[3] = "Three";map[2] = "Two";map[1] = "One";print('The map is $map');// Remove the entry with odd keysmap.removeWhere((key, value){return key % 2 != 0;});print('The map is $map');}
Explanation
-
Line 1: We import the
collectionlibrary. -
Line 4: We create a new
SplayTreeMapobject with the namemap. We pass acomparefunction as an argument. This function is used to maintain the order of themapentries. In our case, thecomparefunction orders the elements in descending order. -
Lines 7 to 11: We add five new entries to the
map. Now, the map is{5: Five, 4: Four, 3: Three, 2: Two, 1: One}. -
Line 16: We use the
removeWhere()method with atestfunction as an argument. Thetestfunction returnstrueif the key is an odd value. In our case, the keys1,3, and5are the values, so these entries are removed from the map. After removing the odd value entries, the map will be{4: Four, 2: Two}.