aspose file tools
The moose likes Java in General and the fly likes collection with Duplicate key Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "collection with Duplicate key" Watch "collection with Duplicate key" New topic
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
    
    3

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
    
    7

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?
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: collection with Duplicate key
 
Similar Threads
Cookies doubt
Linked hashmap issue
Map with duplicate keys
Problem in executing 'executeUpdate()' method in for loop
Collections/HashMap and threads