如何在地图中使用具有多个值的键?

use*_*121 5 java map

我有这样的地图

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());
}
Run Code Online (Sandbox Code Playgroud)

上述计划的输出是

There are 2 elements in the map.
Content of Map are...
b   10  104
a   30  127
Run Code Online (Sandbox Code Playgroud)

现在我希望那个键应该有多个值,比如

a 10
a 20
a 30
Run Code Online (Sandbox Code Playgroud)

所以我应该得到一个相关的所有值.请告诉我如何实现同样的目标.通过嵌套集合,我希望键'a'具有所有三个值.

Bri*_*new 13

看过番石榴Multimaps了吗?

类似于Map的集合,但可以将多个值与单个键相关联.如果使用相同的键但不同的值调用put(K,V)两次,则multimap包含从键到两个值的映射.

如果你真的想使用标准集合(如下所示),你必须为每个密钥存储一个集合,例如

map = new HashMap<String, Collection<Integer>>();
Run Code Online (Sandbox Code Playgroud)

请注意,您进入一个新的关键是第一次,你必须创建新的集合(List,Set添加第一个值之前等).