Java HashMap:如何通过索引获取密钥和值?

我试图使用HashMap将唯一的字符串映射到字符串ArrayList,如下所示:

HashMap<String, ArrayList> 

基本上,我希望能够通过编号访问密钥,而不是使用密钥的名称。 我希望能够访问所述密钥的值,迭代它。 我想象的是这样的:

 for(all keys in my hashmap) { for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) { // do things with the hashmaps elements } } 

是否有捷径可寻?

您可以通过调用map.keySet()来迭代键,或者通过调用map.entrySet()遍历条目。 迭代条目可能会更快。

 for (Map.Entry> entry : map.entrySet()) { List list = entry.getValue(); // Do things with the list } 

如果要确保以插入它们的相同顺序迭代键,则使用LinkedHashMap

顺便说一句,我建议将声明的地图类型更改为> 。 总是最好根据接口而不是实现来声明类型。

如果您真的只想要第一个键的值,这是一般解决方案

 Object firstKey = myHashMap.keySet().toArray()[0]; Object valueForFirstKey = myHashMap.get(firstKey); 

除非您使用LinkedHashMapSortedMap ,否则不会对HashMaps进行排序。 在这种情况下,您可能需要LinkedHashMap 。 这将按插入顺序迭代(或者如果您愿意,按照上次访问的顺序)。 在这种情况下,它会

 int index = 0; for ( Map.Entry> e : myHashMap.iterator().entrySet() ) { String key = e.getKey(); ArrayList val = e.getValue(); index++; } 

地图中没有直接的get(索引),因为它是一个无序的键/值对列表。 LinkedHashMap是一种保持订单的特殊情况。

 for (Object key : data.keySet()) { String lKey = (String) key; List list = data.get(key); } 

已选择解决方案。 但是,我为那些想要使用替代方法的人发布了这个解决方案:

 // use LinkedHashMap if you want to read values from the hashmap in the same order as you put them into it private ArrayList getMapValueAt(LinkedHashMap> hashMap, int index) { Map.Entry> entry = (Map.Entry>) hashMap.entrySet().toArray()[index]; return entry.getValue(); } 

你可以做:

 for(String key: hashMap.keySet()){ for(String value: hashMap.get(key)) { // use the value here } } 

这将迭代每个键,然后列表与每个键关联的每个值。

HashMaps不会按特定顺序保留您的键/值对。 它们基于每个键从其Object.hashCode()方法返回的哈希值进行排序。 但是,您可以使用迭代器迭代一组键/值对:

 for (String key : hashmap.keySet()) { for (list : hashmap.get(key)) { //list.toString() } } 

如果你不关心实际的键,迭代所有 Map值的简洁方法是使用它的values()方法

 Map> myMap; for ( List stringList : myMap.values() ) { for ( String myString : stringList ) { // process the string here } } 

values()方法是Map接口的一部分,并返回地图中值的Collection视图。