作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有这样一张 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>>();
请注意,第一次输入新键时,您必须在添加第一个值之前创建新集合(List
、Set
等)。
关于java - 如何在 map 中拥有具有多个值的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13720225/
我是一名优秀的程序员,十分优秀!