| Author |
collection with Duplicate key
|
Mohanasundar Nagarajan
Greenhorn
Joined: Mar 23, 2010
Posts: 19
|
|
Hi,
Java reference says that a Map, HashMap or Hashtable does not allow to store multiple entries with a same key. I have the requirement to store multiple entries (basically key will repeat) into some collection with a same key. Is there any collection to handle such a situation?
Thanks in advance,
Mohanasundar.n
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
If you need use the same key reference multiple values then think about making the values as a List.
So a sample might look like Map<String,List<Object>>.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
|
You could do what John Jai says, or use for example Multimap from Google Guava.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
Jesper de Jong wrote:You could do what John Jai says, or use for example Multimap from Google Guava.
Yes, when is regular Java going to get a Multimap implementation?
@Mohana: Just to add a wrinkle to John's post, another option you might want to consider is a Map<Key,Set<Value>>. One slight advantage of that setup is that you can't store duplicate (ie, equal()) values for the same key, which may or may not be what you want. If it is, then it's probably the way to go.
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
 |
|
|
subject: collection with Duplicate key
|
|
|