Home > OS >  Find key in map of List (Set) by one of List (Set) values
Find key in map of List (Set) by one of List (Set) values

Time:11-02

In Map<String, Set<Type>> I want to find key which contains Set which contains given Type (Value of Set).

Have:

final map = <String, Set<Type>>{
  'key1': <Type>{
    Type1,
    Type2,
  },
  'key2': <Type>{
    Type3,
    Type4,
  },
}

Want:

find(map, Type3); // 'key2'

CodePudding user response:

You can use Map#entries with firstWhere (or firstWhereOrNull from package:collection)

import 'package:collection/collection.dart';

typedef Type1 = int;
typedef Type2 = double;
typedef Type3 = String;
typedef Type4 = Object;

void main() {
  final map = <String, Set<Type>>{
    'key1': <Type>{
      Type1,
      Type2,
    },
    'key2': <Type>{
      Type3,
      Type4,
    },
  };

  final search = Type3;
  print(
    map.entries.firstWhereOrNull(
      (entry) => entry.value.contains(search),
    )?.key,
  );
}
  • Related