gpt4 book ai didi

java - 如何在 map 中拥有具有多个值的键?

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:28 25 4
gpt4 key购买 nike

我有这样一张 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());
}

上述程序的输出是

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

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

a 10
a 20
a 30

所以我应该得到与 a 关联的所有值。请告知我怎样才能实现同样的目标。通过嵌套集合,我希望键“a”具有所有三个值。

最佳答案

你检查过了吗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.

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

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

请注意,第一次输入新键时,您必须在添加第一个值之前创建新集合(ListSet 等)。

关于java - 如何在 map 中拥有具有多个值的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13720225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com