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);
    }

}
}
4
  • Java Map is a One-To_one object, hence only the last value entered is being pulled from the map. Commented Aug 4, 2015 at 12:40
  • what do you mean selectively display two Commented Aug 4, 2015 at 12:40
  • possible duplicate of Does adding a duplicate value to a HashSet/HashMap replace the previous value Commented Aug 4, 2015 at 12:42
  • only display the key "two", not all key in the map Commented Aug 4, 2015 at 12:43

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

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).
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.