【问题标题】:Is there any data structure similar to HashMap where I can add duplicate keys是否有任何类似于 HashMap 的数据结构,我可以在其中添加重复键
【发布时间】:2012-06-08 00:44:29
【问题描述】:
HashMap<String, String> roleRightsID = new  HashMap<String, String>();

是否有任何类似于 HashMap 的数据结构可以添加重复键

举例

USA, New York
USA, Los Angeles
USA, Chicago
Pakistan, Lahore
Pakistan, Karachi

【问题讨论】:

    标签: java hashmap key-value


    【解决方案1】:

    您需要的称为多重映射,但它在标准 Java 中不存在。在您的情况下,可以使用Map&lt;String, List&lt;String&gt;&gt; 进行模拟。

    您可以在此处找到一个示例:http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html,在 Multimaps 部分中。

    Apache Commons Collections 中还有一个MultiMap,如果您不想重复使用前面的示例,可以使用它。

    【讨论】:

      【解决方案2】:

      如果您需要在一个键中保留几个值,您可以使用HashMap&lt;String,List&lt;String&gt;&gt;

      例子

      HashMap<String,List<String>> map=new HashMap<String,List<String>>();
      
      //to put data firs time
      String country="USA";
      //create list for cities
      List<String> cityList=new ArrayList<String>();
      //then fill list
      cityList.add("New York");
      cityList.add("Los Angeles ");
      cityList.add("Chicago");
      
      //lets put this data to map
      map.put(country, cityList);
      
      //same thind with other data
      country="Pakistan";
      cityList=new ArrayList<String>();
      cityList.add("Lahore");
      cityList.add("Karachi");
      map.put(country, cityList);
      
      //now lets check what is in map
      System.out.println(map);
      
      //to add city in USA
      //you need to get List of cities and add new one 
      map.get("USA").add("Washington");
      
      //to get all values from USA
      System.out.println("city in USA:");
      List<String> tmp=map.get("USA");
      for (String city:tmp)
          System.out.println(city);
      

      【讨论】:

        【解决方案3】:

        重复键通常是不可能的,因为它违反了唯一键的概念。您可以通过创建一个结构来表示您的数据并将 ID 号或唯一键映射到另一组对象来完成类似的操作。

        例如:

        class MyStructure{
              private Integer id
              private List<String> cityNames
        }
        

        那么你可以这样做:

         Map<Integer, MyStructure> roleRightsId = new HashMap<Integer, MyStructure>()
         MyStructure item = new MyStructure()
         item.setId(1)
         item.setCityNames(Arrays.asList("USA", "New York USA")
         roleRightsId.put(item.getId(), item)
        

        但我可能会错过您想要完成的任务。您能否进一步描述您的需求?

        【讨论】:

          【解决方案4】:

          在常规哈希图中使用字符串-> 列表映射。这可能是一种存储数据的方式。

          【讨论】:

            【解决方案5】:

            问题变成了,当你get()其中一个重复键时,你想返回什么?

            通常最终发生的是您返回 List 的项目。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-07-12
              • 1970-01-01
              • 1970-01-01
              • 2011-07-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-08-20
              相关资源
              最近更新 更多