How to iterate through LinkedHashMap with lists as values

P basak picture P basak · Sep 7, 2012 · Viewed 162.1k times · Source

I have following LinkedHashMap declaration.

LinkedHashMap<String, ArrayList<String>> test1

my point is how can i iterate through this hash map. I want to do this following, for each key get the corresponding arraylist and print the values of the arraylist one by one against the key.

I tried this but get only returns string,

String key = iterator.next().toString();  
ArrayList<String> value = (ArrayList<String> )test1.get(key)

Answer

matt b picture matt b · Sep 7, 2012
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.