简体   繁体   中英

Displaying key-values in HashMap

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

}
}

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

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, ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM