Home > Software engineering >  get key from Map<String,List<String>> knowing one of the List values
get key from Map<String,List<String>> knowing one of the List values

Time:12-14

I have a map

Map<String, List> map1 = {a: [1,2,3,4], b: [5,6,7,8], c: [9,10,11]};

I know one of the values of one of the lists - 1..11. How can I get the key of a map entity where this value belongs to - a, b, c?

CodePudding user response:

Try this, where search is the value you're trying to find in the array.

Note that firstWhere can give you an error if the value cannot be found anywhere.

void main() {
  final data = {
    'a': [1, 2, 3, 4],
    'b': [5, 6, 7, 8],
    'c': [9, 10, 11]
  };

  final search = 4;

  final selected = data.keys.firstWhere((key) {
    return data[key]!.contains(search);
  });

  print(selected); // a
}

CodePudding user response:

I found a solution

int valueToLookFor = 5;

String keyName = map1.keys.firstWhere((key) => map1[key]!.contains(valueToLookFor));
  • Related