39

The Map interface doesn't seem to provide access to the entries as an iterable, nor does it expose a where method to filter entries. Am I missing something? Is there a simple workaround?

e.g.

Map map;
final filteredMap = map.where((k, v) => k.startsWith("foo"));

6 Answers 6

54

Update: with control flow collection statements you can also do this:

final filteredMap = {
  for (final key in map.keys)
    if (!key.startsWith('foo')) key: map[key]
};

Original answer: Dart 2.0.0 added removeWhere which can be used to filter Map entities. Given your example, you could apply this as:

Map map;
final filteredMap = Map.from(map)..removeWhere((k, v) => !k.startsWith("foo"));

It's not the where method you asked for, but filtering Map entities is certainly doable this way.

7
  • 2
    Maybe this is not not the perfect anser as you said, but it really fits to me, thanks!
    – dmarquina
    Commented Apr 19, 2019 at 9:16
  • 2
    What's the ".." ? I am just learning and find it impossible to search for it. Will be grateful if someone could shed some light on this. Commented Nov 9, 2020 at 16:24
  • 3
    @lost-and-found it's the cascade notation: dart.dev/guides/language/language-tour#cascade-notation- Commented Nov 9, 2020 at 18:45
  • 1
    @AndrásSzepesházi Thank you very much. This also looks like a page I would want to spend some time reading. :) Commented Nov 9, 2020 at 23:59
  • 1
    Note that you should prefer Map.of instead of Map.from unless you want to create a new map with more precise types than the original one.
    – Stuck
    Commented Mar 22, 2021 at 22:03
7

Since Dart 2.0 Maps have an entries getter that returns an Iterable<MapEntry<K, V>> so you can do:

MapEntry theOne = map.entries.firstWhere((entry) {
        return entry.key.startsWith('foo');
      }, orElse: () => MapEntry(null, null));
1
  • using your suggestion yields this error message type '() => MapEntry<dynamic, dynamic>' is not a subtype of type '() => MapEntry<String, dynamic>' of 'orElse'
    – Gotama
    Commented Mar 1, 2020 at 19:43
6

You can use

library x;

void main(List<String> args) {
  Map map = {'key1': 'aölsjfd', 'key2': 'oiweuwrow', 'key11': 'oipoip', 'key13': 'werwr'};

  final filteredMap = new Map.fromIterable(
      map.keys.where((k) => k.startsWith('key1')), key: (k) => k, value: (k) => map[k]);

  filteredMap.forEach((k, v) => print('key: $k, value: $v'));
}
2
2

I use dartx and it's filter method

  var myMap = {
    "a": [1, 2, 3],
    "b": [4, 5, 6],
    "c": [7, 8, 9],
  };

  var result = myMap.filter((entry) => entry.key != "a");
1

You can just create an extension function and then use it anywhere in your code.

Put this in any file (I called mine MapUtils.dart)

extension MapUtils<K, V> on Map<K, V> {

  Map<K, V> where(bool Function(K, V) condition) {
    Map<K, V> result = {};
    this.entries.forEach((element) {
      if (condition(element.key, element.value)) {
        result[element.key] = element.value;
      }
    });
    return result;
  }
}

and then use it like so:

Map<String, int> peopleHeight = {"Bob":170, "Alice":130};
Map<String, int> shortPeople = peopleHeight.where((name, height) => height < 140);

1

You can still use the simple where() function:

final filtered = Map.fromEntries(original.entries.where((item) => ...));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.