HashMap roleRightsID = new HashMap();
是否存在类似于HashMap的数据结构,我可以在其中添加重复的密钥
例如
美国,纽约 美国,洛杉矶 美国,芝加哥 巴基斯坦,拉合尔 巴基斯坦,卡拉奇
等
答案 0 :(得分:5)
您需要的是多重映射,但它在标准Java中不存在。在您的情况下,可以使用Map<String, List<String>>
进行模拟。
您可以在这里找到一个示例:http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html,在Multimaps部分。
如果您不想重复使用上一个示例,MultiMap中还有一个Apache Commons Collections可供您使用。
答案 1 :(得分:4)
如果您需要在一个键中保留少量值,则可以使用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);
答案 2 :(得分:1)
重复密钥通常是不可能的,因为它会违反唯一密钥的概念。您可以通过创建表示数据的结构并将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)
但我可能会错过你想要完成的事情。你能进一步描述一下你的需求吗?
答案 3 :(得分:0)
使用字符串 - &gt;列出常规散列映射中的映射。这可能是存储数据的一种方式。
答案 4 :(得分:0)
问题变成了,当您get()
其中一个重复的密钥时,您想要返回什么?
通常最终会发生的事情是您返回List
个项目。