Iterate in Map<List, String>

Asked

Viewed 331 times

0

How to iterate on a Mapof the kind Map<List, String>? List all values, pay key value: [1, 'A'].

void main() {
  print(_mapList.map);
  //??
  // _mapList.map((i, s) =>{

  // });
}

Map<List, String> _mapList = {
  [1, 'A']: "1A",
  [2, 'B']: "2A"
};

3 answers

2

I already went through this problem a while ago and searching the inner classes I found the following:

  /**
   * Creates a Map instance with the default implementation, [LinkedHashMap].
   *
   * This constructor is equivalent to the non-const map literal `<K,V>{}`.
   *
   * A `LinkedHashMap` requires the keys to implement compatible
   * `operator==` and `hashCode`, and it allows null as a key.
   * It iterates in key insertion order.
   */

In that hint it says that the Key must be compatible with the operator == and a List is not compatible.

So whenever you do _mapList[[1, 'A']] will receive a NULL in response.

Example

Follow an example to better understand:

void main() {
  List a = [1, 2];
  List b = [1, 2];

  String c = "Teste";
  String d = "Teste";

  print(a == b); // return false
  print(c == d); // return true
}

You can rotate on dartpad.

Workaround

When I came across this, I turned into my own List in a String and working with her that way...

You can enter in your Map to Key as a text "[1, 'B']": "1B" and if you need to work with Key in list format, just do

jsonDecode(Key); // Return [1, 'B'] (List)

1


To list all elements:

  _mapList.entries.forEach((entry) {
    print('${entry.key}: ${entry.value}');
  });
// resultado: 
// [1, A]: 1A
// [2, B]: 2A

To get the value of the key [1, 'A'] is not so trivial, because the key is a list (and very well explained by @Matheus Ribeiro).

So a solution would be to force a search for the key elements inside the map entries:

  final value = _mapList.entries.firstWhere((entry) => entry.key[0] == 1 && entry.key[1] == 'A').value;
  print(value); // 1A

Or if this is used many times, encapsulate in an auxiliary method:

  String _getListElementFromMap(Map<List, String> map, int firstElement, String secondElement) {
    return map.entries.firstWhere((entry) => entry.key[0] == firstElement && entry.key[1] == secondElement).value;
  } 

  print(_getListElementFromMap(_mapList, 1, 'A')); // 1A
  print(_getListElementFromMap(_mapList, 2, 'B')); // 2A

1

As another suggestion to the other answer, you can use the method foreach to iterate over all elements of a Map:

 Map<List, String> _mapList = {
    [1, 'A']: "1A",
    [2, 'B']: "2A"
  };


  _mapList.forEach((k, v) {
       print(k);
       print(v);
   });

If you want to compare and discover the value of a specific key, another workaround is you use the class functions Listequality (Note the import at the beginning):

import 'package:collection/collection.dart';

 Map<List, String> _mapList = {
    [1, 'A']: "1A",
    [2, 'B']: "2A"
  };


_mapList.forEach((k, v) {
       if(ListEquality().equals(k, [1,'A']))
           print (v);
   });

Keep in mind that this is a solution that must iterate over all elements of the dictionary, so you will lose the average access time feature. The complexity of the access time will change from O(1) for O(n). Therefore, it may take longer for larger dictionaries.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.