Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()+""+m.getValue()+""+ 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
104 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...