Search code examples
javacollectionslinkedhashmap

How to iterate through LinkedHashMap with lists as values


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)

Solution

  • 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>>.