Java HashMap: How to get a key and value by index?
You can iterate over keys by calling map.keySet()
, or iterate over the entries by calling map.entrySet()
. Iterating over entries will probably be faster.
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Do things with the list
}
If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap
.
By the way, I'd recommend changing the declared type of the map to <String, List<String>>
. Always best to declare types in terms of the interface rather than the implementation.
Here is the general solution if you really only want the first key's value
Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);
HashMaps are not ordered, unless you use a LinkedHashMap
or SortedMap
. In this case, you may want a LinkedHashMap
. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would be
int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
String key = e.getKey();
ArrayList<String> val = e.getValue();
index++;
}
There is no direct get(index) in a map because it is an unordered list of key/value pairs. LinkedHashMap
is a special case that keeps the order.