Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any data structure similar to HashMap where I can add duplicate keys

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

like image 325
Androider Avatar asked Jun 03 '12 18:06

Androider


People also ask

Which data structure can have duplicate keys?

One of these data structures is called Multimap and it allows us to store duplicate keys in a more elegant fashion.

Can I add duplicate key into a HashMap?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Does tree map allow duplicate keys?

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.

Does Hashtable allow duplicate keys?

Hashtable FeaturesIt does not accept duplicate keys. It stores key-value pairs in hash table data structure which internally maintains an array of list.


1 Answers

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.

like image 73
tofcoder Avatar answered Sep 20 '22 18:09

tofcoder