How can I filter a map / access the entries

前端 未结 3 911
一生所求
一生所求 2021-02-18 23:46

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 w

相关标签:
3条回答
  • 2021-02-19 00:07

    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));
    
    0 讨论(0)
  • 2021-02-19 00:11

    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.

    0 讨论(0)
  • 2021-02-19 00:18

    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'));
    }
    
    0 讨论(0)
提交回复
热议问题