Flattening a HashMap of (String → ArrayList) to an ArrayList I have one HashMap&lt;String, ArrayList&lt;String&gt;&gt; and I want to concatenate a key with every item in its ArrayList.

Consider the following demo program:

HashMap&lt;String, ArrayList&lt;String&gt;&gt; map1 = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();

        ArrayList&lt;String&gt; map11 = new ArrayList&lt;String&gt;();
        map11.add("a");
        map11.add("b");
        map1.put("1", map11);

        ArrayList&lt;String&gt; map12 = new ArrayList&lt;String&gt;();
        map12.add("c");
        map12.add("d");
        map1.put("2", map12);

ArrayList&lt;String&gt; finalList = new ArrayList&lt;String&gt;();
        for (Entry&lt;String, ArrayList&lt;String&gt;&gt; ent : map1.entrySet()) {
            ArrayList&lt;String&gt; ls = ent.getValue();
            for (String string : ls) {
                finalList.add(ent.getKey()+" = "+string);
            }
        }


This is working fine and giving expected output. The value of finalList after executing program is:


  [1 = a, 1 = b, 2 = c, 2 = d]


If there is any better and faster way to do this, please let me know. In the actual project ArrayList, every HashMap entry contains thousands of items.
If it's really a list of entries that you want, then this is about as fast as it gets.

But it can be better:


Use interface types instead of implementations, for example List instead of ArrayList and Map instead of HashMap
Java 6 is no longer supported, and in Java 7 you should use the diamond operator to create new instances, for example: Map&lt;String, List&lt;String&gt;&gt; map1 = new HashMap&lt;&gt;();
Use better, more natural names, for example:

entry is better than ent
list is better than ls

Use unit tests to verify your implementation


Based on the above, here's an alternative implementation:

public static List&lt;String&gt; concatMapEntries(Map&lt;String, List&lt;String&gt;&gt; map) {
    List&lt;String&gt; finalList = new ArrayList&lt;&gt;();
    for (Map.Entry&lt;String, List&lt;String&gt;&gt; entry : map.entrySet()) {
        List&lt;String&gt; list = entry.getValue();
        for (String string : list) {
            finalList.add(entry.getKey() + " = " + string);
        }
    }
    return finalList;
}


And unit test:

@Test
public void testExample() {
    Map&lt;String, List&lt;String&gt;&gt; map1 = new HashMap&lt;&gt;();

    List&lt;String&gt; map11 = new ArrayList&lt;&gt;();
    map11.add("a");
    map11.add("b");
    map1.put("1", map11);

    List&lt;String&gt; map12 = new ArrayList&lt;&gt;();
    map12.add("c");
    map12.add("d");
    map1.put("2", map12);

    assertEquals("[1 = a, 1 = b, 2 = c, 2 = d]", concatMapEntries(map1).toString());
}