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?
Here is the general solution if you really only want the first key's value
A solution is already selected. However, I post this solution for those who want to use an alternative approach:
You can do:
This will iterate over every key, and then every value of the list associated with each key.
HashMaps are not ordered, unless you use a
LinkedHashMap
orSortedMap
. In this case, you may want aLinkedHashMap
. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would beThere 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.HashMaps don't keep your key/value pairs in a specific order. They are ordered based on the hash that each key's returns from its Object.hashCode() method. You can however iterate over the set of key/value pairs using an iterator with: