Reputation: 3585
In my android app, I'm trying to get all values of single key using hash map. Below is my code. but I am getting only one value "maharashtra" for key "blr" and not "banglore" (in my code). What am I missing?
HashMap<String, String> myMap = new HashMap<String, String>();
myMap.put("ind", "india");
myMap.put("tn", "tamilnadu" + " How");
myMap.put("blr","bangalore");
myMap.put("blr","maharashtra");
Set<Entry<String,String>> set = myMap.entrySet();
for (Map.Entry<String, String> me : set) {
if(me.getKey().equals("blr")){
System.out.println(me.getValue());
}
}
Upvotes: 0
Views: 1485
Reputation: 3585
Finally got solution. Awesom...
import java.util.HashMap;
import java.util.Map;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class hashmap {
/**
* @param args
*/
public static void main(String[] args) {
// HashMap<String, List<String> > myMap = new HashMap<String, List<String> >();
Map<String,List<String>> myMap = new HashMap<String,List<String>>();
List<String> arr4 = new ArrayList<String>();
arr4.add("india");
arr4.add("tamilnadu");
arr4.add("tamilnadu");
arr4.add("tamilnadu");
arr4.add("tamilnadu");
myMap.put("tn", arr4);
Set<Entry<String,List<String>>> set = myMap.entrySet();
for (Map.Entry<String, List<String>> me : set) {
if(me.getKey().equals("tn")){
System.out.println(me.getValue());
}
}
}
}
Upvotes: 1
Reputation: 416
Probably you should use HashMap<String, List<String>>
instead of HashMap<String, String>
.
To add element to map :
yMap.put("blr", new ArrayList<String>());
yMap.get("blr").add("maharashtra");
Upvotes: 0
Reputation:
First of all: you can't. As stated here:
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Please read: http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Second: If you are using a Key, Value structure you most likely shouldn't think of ever having duplicate keys, it defeats the purpose of a Key, Value collection.
A simple solution would be to use HashMap<String, List<String>>
instead of HashMap<String, String>
. Storing all the values in the List<String>
.
Upvotes: 3
Reputation: 2348
the keys are unique. so you are simply just overwriting the first assignment
myMap.put("blr","bangalore");
with
myMap.put("blr","maharashtra");
so, use another key!?
Upvotes: 0
Reputation: 23164
the point of a hashmap is that keys are unique. so you are overwriting bangalore
with maharashtra
with myMap.put("blr","maharashtra");
Upvotes: 0