I am trying to use a HashMap to map a unique string to a string ArrayList like this:
HashMap<String, ArrayList<String>>
Basically, I want to be able to access the keys by number, not by using the key's name. And I want to be able to access said key's value, to iterate over it. I'm imagining something like this:
for(all keys in my hashmap) {
for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) {
// do things with the hashmaps elements
}
}
Is there an easy way to do this?
If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its
values()
methodThe
values()
method is part of the Map interface and returns a Collection view of the values in the map.You can iterate over keys by calling
map.keySet()
, or iterate over the entries by callingmap.entrySet()
. Iterating over entries will probably be faster.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.