具有重复键的映射实现

新手上路,请多包涵

我想要一张带有重复键的地图。

我知道有很多地图实现(Eclipse 向我显示了大约 50 个),所以我敢打赌一定有一个允许这样做。我知道编写自己的地图很容易做到这一点,但我宁愿使用一些现有的解决方案。

也许是 commons-collections 或 google-collections 中的东西?

原文由 IAdapter 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 610
2 个回答

您正在搜索多图,实际上 commons-collections 和 Guava 都有多个实现。 Multimaps 通过为每个键维护一个值集合来允许多个键,即您可以将单个对象放入映射中,但您检索一个集合。

如果你可以使用 Java 5,我更喜欢 Guava 的 Multimap 因为它是泛型感知的。

原文由 nd. 发布,翻译遵循 CC BY-SA 3.0 许可协议

我们不需要依赖 Google Collections 外部库。您可以简单地实现以下地图:

 Map<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList>();

public static void main(String... arg) {
   // Add data with duplicate keys
   addValues("A", "a1");
   addValues("A", "a2");
   addValues("B", "b");
   // View data.
   Iterator it = hashMap.keySet().iterator();
   ArrayList tempList = null;

   while (it.hasNext()) {
      String key = it.next().toString();
      tempList = hashMap.get(key);
      if (tempList != null) {
         for (String value: tempList) {
            System.out.println("Key : "+key+ " , Value : "+value);
         }
      }
   }
}

private void addValues(String key, String value) {
   ArrayList tempList = null;
   if (hashMap.containsKey(key)) {
      tempList = hashMap.get(key);
      if(tempList == null)
         tempList = new ArrayList();
      tempList.add(value);
   } else {
      tempList = new ArrayList();
      tempList.add(value);
   }
   hashMap.put(key,tempList);
}

请确保微调代码。

原文由 user668943 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题