• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to handle duplicate keys in java

 
Shruthi Babu
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a scenario where in I need key value pairs .. But the keys can be unique ? How should I handle them

Guess HashMap does not allow unique key values

the keys should be a list objects for me ...

Any help is highly appreciated
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain your problem clearly. It looks like you are confusing "unique" and "non-unique". HashMap requires that keys are unique.

The Apache Jakarta Commons Collections library contains extra collection classes that aren't in the standard Java API. Maybe class MultiKeyMap or MultiValueMap in that library is what you are looking for?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you typed "unique" when you meant "duplicate". "HashMap does not allow duplicate keys." is true.

This is a common enough problem that the solution has a name: MultiMap. You can find implementations of MultiMap in the Apache Commons and other places, but the idea is so simple you can make your own.

The idea is for each key we store a List of values instead of a single value. Here's how put works in a class that has a map as a member variable. Can you imagine get?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic