File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How to handle duplicate keys in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to handle duplicate keys in java" Watch "How to handle duplicate keys in java" New topic

How to handle duplicate keys in java

Shruthi Babu
Ranch Hand

Joined: May 04, 2007
Posts: 54
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

Joined: Aug 16, 2005
Posts: 15081

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?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: How to handle duplicate keys in java
It's not a secret anymore!