0

I need a collection in Java that is going to store a pair, a key and a value.

So I decided to use a HashMap<String,String>, but I noticed that when I try to add a key that already exists, the previous (key,value) is replaced by the new one (NewKey,NewValue) and the previous entry is lost. So when I have duplicate keys, the previous key is replaced by the new one.

How can I have a HashMap with duplicate keys?

Luiggi Mendoza
  • 83,472
  • 15
  • 149
  • 315
programmer
  • 4,041
  • 13
  • 47
  • 59

2 Answers2

3

you need MultiMap, take a look at Google Guava Multimap

Eugen Halca
  • 1,765
  • 2
  • 12
  • 25
2

If you want to map a key to a collection of values, take a look at Guava's Multimap. If you don't want to use a third-party library, you can simulate a Multimap with a Map<String, Collection<String>>. The Java tutorial on the Map interface has an example of implementing a Multimap.

drac_o
  • 375
  • 3
  • 11
Ted Hopp
  • 227,407
  • 48
  • 383
  • 507