0

I am have the Hashmap like this,

HashMap<String,String> epnSource = new HashMap<String, String>();

Now I have added the keys/values like this,

epnSource.put("10.3.2.227","EPN1");
epnSource.put("10.3.2.227","EPN2");
epnSource.put("10.3.2.166","EPN3");
epnSource.put("10.3.2.166","EPN4");
epnSource.put("10.3.2.161","EPN5");

I am trying to do every time before adding a value, I want to check number of occurrences of a key present in the HashMap. Suppose if key 10.3.2.227 has more than two occurrences I shouldn't added it and go for new one. Any suggestions will be helpful.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Vinesh
  • 933
  • 2
  • 7
  • 22
  • 2
    Well I believe if it's a HashMap it can't have more than 1 of the same key, which 10.3.2.227 looks like it's a Key. Edit: If you want to have more than 1 value for a single key, it look this http://stackoverflow.com/questions/4956844/hashmap-with-multiple-values-under-the-same-key covers that. – Austin Sep 25 '12 at 06:25
  • 1
    Your assumption that hashMap has multiple entries for a single key is wrong. – Zaki Sep 25 '12 at 06:27
  • Did you trying adding those entries and print the map at the end to check if all the entries are intact? You may want to do that first. also, is your map modified by multiple threads? – Vikdor Sep 25 '12 at 06:27

2 Answers2

4

Suppose if value 10.3.2.227 has more than two occurrences ...

It won't. The way that you have implemented it, the "10.3.2.227" is a key of the Map, and a given key cannot appear more than once in a Map.

If you want a given key (e.g. "10.3.2.227") to map to multiple values (e.g. "EPN1" and "EPN1"), you need to use either a Map<String,Set<String>> or a MultiMap class from the Apache or Google/Guava collections libraries.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

If the map previously contained a mapping for the key, the old value is replaced.

It is not possible duplicate key in HashMap.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103