Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a key with multiple values in a map?

Tags:

java

map

I have a map like this

Map map=new HashMap();//HashMap key random order.
map.put("a",10);
map.put("a",20);
map.put("a",30);
map.put("b",10);

System.out.println("There are "+map.size()+" elements in the map.");
System.out.println("Content of Map are...");
Set s=map.entrySet();
Iterator itr=s.iterator();
while(itr.hasNext())
{
    Map.Entry m=(Map.Entry)itr.next();
    System.out.println(m.getKey()+"\t"+m.getValue()+"\t"+ m.hashCode());
}

Output of the above program is

There are 2 elements in the map.
Content of Map are...
b   10  104
a   30  127

Now I want that key a should have multiple values like

a 10
a 20
a 30

So that I should get all the values associated by a. Please advise how can I achieve that same thing. By nesting of collections, I want key 'a' to have all the three values.

like image 437
user1876121 Avatar asked Dec 05 '12 09:12

user1876121


2 Answers

Have you checked out Guava Multimaps ?

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

If you really want to use standard collections (as suggested below), you'll have to store a collection per key e.g.

map = new HashMap<String, Collection<Integer>>();

Note that the first time you enter a new key, you'll have to create the new collection (List, Set etc.) before adding the first value.

like image 161
Brian Agnew Avatar answered Sep 30 '22 07:09

Brian Agnew


To implement what you want using the Java standard library, I would use a map like this:

Map<String, Collection<Integer>> multiValueMap = new HashMap<String, Collection<Integer>>();

Then you can add values:

multiValueMap.put("a", new ArrayList<Integer>());
multiValueMap.get("a").add(new Integer(10));
multiValueMap.get("a").add(new Integer(20));
multiValueMap.get("a").add(new Integer(30));

If this results uncomfortable for you, consider wrapping this behaviour in a dedicated Class, or using a third-party solution, as others have suggested here (Guava Multimap).

like image 26
think01 Avatar answered Sep 30 '22 08:09

think01