Is there any data structure similar to HashMap where I can add duplicate keys
Solution 1
What you need is called a multimap, but it is does not exist in standard Java. It can be simulated with a Map<String, List<String>>
in your case.
You can find an example here: http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html, in the Multimaps section.
There is also a MultiMap in the Apache Commons Collections that you could use if you do not want to reuse the previous example.
Solution 2
You can use HashMap<String,List<String>>
if you need to keep few values in one key.
Example
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);
Solution 3
Duplicate keys are generally impossible, as it would violate the notion of a unique key. You might be able to accomplish something close to this by creating a structure to represent your data and mapping an ID number or unique key to another set of objects.
For example:
class MyStructure{
private Integer id
private List<String> cityNames
}
Then you can do:
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)
But I could be missing what you are trying to accomplish. Could you describe your need a further?
Comments
-
Androider almost 2 years
HashMap<String, String> roleRightsID = new HashMap<String, String>();
is there any data structure similar to HashMap where I can add duplicated keys
For Example
USA, New York USA, Los Angeles USA, Chicago Pakistan, Lahore Pakistan, Karachi
etc