Dart Map removeWhere()
Syntax & Examples


Syntax of Map.removeWhere()

The syntax of Map.removeWhere() method is:

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

This removeWhere() method of Map removes all entries of this map that satisfy the given test.

Parameters

ParameterOptional/RequiredDescription
testrequiredthe function that determines if an entry should be removed

Return Type

Map.removeWhere() returns value of type void.



✐ Examples

1 Remove entries with even values

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the removeWhere() method with a function that removes entries with even values.
  3. The entries with even values ('two': 2) are removed from the map.
  4. The updated map map is printed, showing the remaining entries.

Dart Program

void main() {
  Map<String, int> map = {'one': 1, 'two': 2, 'three': 3};
  map.removeWhere((key, value) => value % 2 == 0);
  print(map); // Output: {one: 1, three: 3}
}

Output

{one: 1, three: 3}

2 Remove entries with values of length 3

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the removeWhere() method with a function that removes entries with values of length 3.
  3. The entry with value 'One' and 'Two' are removed from the map, because of their length being 3.
  4. The updated map map is printed, showing the remaining entries.

Dart Program

void main() {
  Map<int, String> map = {1: 'One', 2: 'Two', 3: 'Three'};
  map.removeWhere((key, value) => value.length == 3);
  print(map); // Output: {1: One}
}

Output

{3: Three}

3 Remove entries with keys starting with 't'

In this example,

  1. We create a map map with some key-value pairs.
  2. We use the removeWhere() method with a function that removes entries with keys starting with 't'.
  3. The entries with keys 'taste' and 't' are removed from the map.
  4. The updated map map is printed, showing the remaining entries.

Dart Program

void main() {
  Map<String, String> map = {'fruit': 'apple', 'color': 'red', 'taste': 'sweet'};
  map.removeWhere((key, value) => key.startsWith('t'));
  print(map); // Output: {fruit: apple, color: red}
}

Output

{fruit: apple, color: red}

Summary

In this Dart tutorial, we learned about removeWhere() method of Map: the syntax and few working examples with output and detailed explanation for each example.