0

I have 2 questions regarding the code bellow,

1.I have the key "two" twice in my hashmap, while printing, "two" is displayed only once.Why its not displaying "two" twice?

2.How to selectively display the key "two"?

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class main {
public static void main(String[] args){
HashMap<String,String> myMap = new HashMap<String,String>();

    myMap.put("one", "1");
    myMap.put("two", "2");
    myMap.put("three", "3");
    myMap.put("two", "4");

    Set <String> mySet =myMap.keySet();
    Iterator itr = mySet.iterator();

    while(itr.hasNext()){
        String key = (String) itr.next();
        System.out.println(key);
    }

}
}
darijan
  • 9,725
  • 25
  • 38
bharani
  • 81
  • 1
  • 8
  • Java Map is a One-To_one object, hence only the last value entered is being pulled from the map. – Yogev Caspi Aug 04 '15 at 12:40
  • what do you mean selectively display two – GregH Aug 04 '15 at 12:40
  • possible duplicate of [Does adding a duplicate value to a HashSet/HashMap replace the previous value](http://stackoverflow.com/questions/12940663/does-adding-a-duplicate-value-to-a-hashset-hashmap-replace-the-previous-value) – Ankush soni Aug 04 '15 at 12:42
  • only display the key "two", not all key in the map – bharani Aug 04 '15 at 12:43

2 Answers2

3

Hashmaps may only have one key entry per key in their keyset. The second time you put a key-value pair in the map will override the first when you are using the same key for Maps (which include HashMap).

If you want a one-to-many mapping, you can use a Multimap or a HashMap that maps an object to a collection of objects (although Multimap will most likely make this easier for you)

To display a value for a given key, use:

System.out.println(myMap.get(myKey));
System.out.println(myMap.get("two"));
GregH
  • 5,125
  • 8
  • 55
  • 109
  • 1
    actually this is part of the `Map` interface, not something specific to `HashMap`, and it is not something specific to Java, but it is how the map idiom works in general (programming and math and probably more). – hoijui Aug 04 '15 at 12:45
2

Hashtable and HashMap are one-to-one key value store. That means that for one key you can have only one element. You can still achieve what you want with:

HashMap<String, List<String>>

when you add an element to the map, you have to add it to the list for this key, i.e.

public void add(String key, String value) {
    List<String> list = map.get(key);
    if (list == null) { //if the list does not exist, create it, only once
        list = new ArrayList<String>();
        map.put(key, list);
    }
    list.add(value);
}

And now, when you want to get all elements with this key:

List<String> elements = map.get("two");

The list will contain all elements you added.

darijan
  • 9,725
  • 25
  • 38