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
  • 85,076
  • 16
  • 154
  • 332
programmer
  • 4,571
  • 13
  • 49
  • 59

2 Answers2

3

you need MultiMap, take a look at Google Guava Multimap

Eugen Halca
  • 1,775
  • 2
  • 13
  • 26
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
  • 427
  • 5
  • 11
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521