tags:

views:

284

answers:

6

I want to get all the values associated with a key in Map. For e.g,

Map tempMap = new HashMap();
tempMap.put("1","X");
tempMap.put("2","Y");
tempMap.put("3","Z");
tempMap.put("1","ABC");
tempMap.put("2","RR");
tempMap.put("1","RT");

How to retrieve all the values associated with key 1 ?

+3  A: 

can't

try using google collections's Multimap

01
+7  A: 

the thing you must understand is that in a Map, the key is unique.

that means that after

tempMap.put("1","X");

"1" is mapped to "X"

and after

tempMap.put("1","ABC");

"1" is mapped to "ABC" and the previous value ("X") is lost

chburd
@Anand: if you need to map the same key to several Strings, use a Collection as the value. I.e., define your map something like this: Map<String, Collection<String>> tempMap.
Jonik
+3  A: 

I think you're missing something important:

Map tempMap = new HashMap();
tempMap.put("1","X");
tempMap.put("2","Y");
tempMap.put("3","Z");
tempMap.put("1","ABC"); // replaces "X"
tempMap.put("2","RR"); // replaces "Y"
tempMap.put("1","RT"); // replaces "ABC"

Also, you should use generics where possible, so your first line should be:

Map<String, String> tempMap = new HashMap<String, String>();
David Grant
+5  A: 

From the HashMap javadoc:

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.

Jérôme
+3  A: 

What you can do is this:

Map<String, List<String>> tempMap = new HashMap<String, List<String>>();
tempMap.put("1", new LinkedList<String>());
tempMap.get("1").add("X");
tempMap.get("1").add("Y");
tempMap.get("1").add("Z");

for(String value : tempMap.get("1")) {
  //do something
}

This compartmentalizes values that correspond to the key "1" into their own list, which you can easily access. Just don't forget to initialize the list... else NullPointerExceptions will come to get you.

Yuval =8-)

Yuval
+1  A: 

To do that you have to associate each key with a Set of values, with corresponding logic to create the set and enter/remove values from it instead of simple put() and get() on the Map.

Or you can use one of the readymade Multimap implementations such as the one in Apache commons.

Michael Borgwardt