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


HashMap<String, String> roleRightsID = new  HashMap<String, String>();

是否有任何类似于哈希图的数据结构,我可以在其中添加重复的键

例如

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

你需要的被称为多映射,但它在标准Java中不存在。在您的案例中,可以使用Map<String, List<String>>进行模拟。

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

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

如果需要在一个键中保留少量值,可以使用HashMap<String,List<String>>

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);

重复键通常是不可能的,因为它会违反唯一键的概念。 您可以通过创建一个结构来表示您的数据并将 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)

但我可能会错过你想要完成的事情。 你能进一步描述一下你的需求吗?

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

问题是,当您get()重复键之一时,您希望返回什么?

通常最终发生的事情是您返回List物品。

相关内容

最新更新