• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

How to handle duplicate keys in java

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic