Unfortunately, the Java Map interface does not allow duplicate keys:
An object that maps keys to values. the card cannot contain duplicate keys; each key can display no more than one value.
Thus, when you try to put a key that already exists on the map, the new value replaces the old value; the reason your iterator iterates 2 times is because there are only 2 elements.
If you want to keep duplicate keys (for example, "a" pointing to 1 and 2), or you can have a list or set map, for example
Map<String, List<Integer>> myMap;
If the list or set that matches the key contains all the values, for example myMap.get("a") , it will return a list that will look like [1,2] .
Or use something like MultiMap from Google or Apache
For your problem, I believe you say you want a special card, where:
- The value for each key is the number of times the key was entered.
- When you iterate over a card, you iterate over all the keys that you added, every time they were added.
You can see how they implemented iterator() for the HashMap , especially by looking at the internal private class of the HashIterator .
next() and hasNext() could continue to return the key as many times as the value specified (i.e. if "Hello" mapped to 2 , your custom iterator () will return using next() "Hello" two times before go to the next key).
A map may not be the right structure to use for what you are trying to do, but I wish you good luck!