You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:15:38