Anand
Anand

Reputation:

How to retrieve all the values associated with a key?

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 ?

Upvotes: 0

Views: 1335

Answers (6)

Michael Borgwardt
Michael Borgwardt

Reputation: 346309

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.

Upvotes: 1

Yuval
Yuval

Reputation: 8087

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

Upvotes: 3

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 2720

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.

Upvotes: 5

David Grant
David Grant

Reputation: 14223

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

Upvotes: 3

chburd
chburd

Reputation: 4159

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

Upvotes: 7

IAdapter
IAdapter

Reputation: 64737

can't

try using google collections's Multimap

Upvotes: 3

Related Questions