• Post Reply Bookmark Topic Watch Topic
  • New Topic

collection with Duplicate key  RSS feed

 
Mohanasundar Nagarajan
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could do what John Jai says, or use for example Multimap from Google Guava.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!