We can use the removeWhere()
method to remove all the entries that satisfy the provided test
condition.
void removeWhere( bool test(K key,V value) )
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.
This method doesn’t return any value.
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');}
Line 1: We import the collection
library.
Line 4: We create a new SplayTreeMap
object with the name map
. We pass a compare
function as an argument. This function is used to maintain the order of the map
entries. In our case, the compare
function 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 a test
function as an argument. The test
function returns true
if the key is an odd value. In our case, the keys 1
, 3
, and 5
are the values, so these entries are removed from the map. After removing the odd value entries, the map will be {4: Four, 2: Two}
.