如何在Map<String, Set<Type>>中通过Set元素查找对应键
实现从
Map<String, Set<Type>>中查找对应Type的键 需求说明
我们需要实现一个方法,传入Map<String, Set<Type>>集合和目标Type,返回集合中包含该Type的对应键(若存在多个匹配,可选择返回第一个或全部)。
实现方案1:返回第一个匹配的键
String? findKeyByType(Map<String, Set<Type>> map, Type targetType) { for (final entry in map.entries) { if (entry.value.contains(targetType)) { return entry.key; } } // 未找到匹配时返回null return null; }
使用示例
void main() { final map = <String, Set<Type>>{ 'key1': <Type>{Type1, Type2}, 'key2': <Type>{Type3, Type4}, }; final matchedKey = findKeyByType(map, Type3); print(matchedKey); // 输出:key2 } // 示例类型定义 class Type1 {} class Type2 {} class Type3 {} class Type4 {}
实现方案2:返回所有匹配的键
如果存在多个Set包含同一个Type的场景,可以返回所有对应的键:
List<String> findAllKeysByType(Map<String, Set<Type>> map, Type targetType) { final matchedKeys = <String>[]; for (final entry in map.entries) { if (entry.value.contains(targetType)) { matchedKeys.add(entry.key); } } return matchedKeys; }
说明
- Dart中的
Type对象可以直接通过contains方法判断是否存在于集合中,无需额外处理。 - 若需要自定义匹配逻辑(比如类型继承关系匹配),可修改
entry.value.contains(targetType)为对应的判断条件。
内容的提问来源于stack exchange,提问作者LacticWhale
相关产品推荐
相关产品推荐

