Tomek Młynarski
Tomek Młynarski

Reputation: 33

How to Iterate through HashMap containing Arraylist

Can you send the implementation how to Iterate through HashMap containing ArrayList, here is my code, I created 2 ArrayLists and added to Hashmap and I need to iterate through

public class t {

public static void main(String[] args) {

    ArrayList<String> a = new ArrayList<String>();
    ArrayList<String> b = new ArrayList<String>();

    a.add("a");
    a.add("b");
    a.add("c");

    b.add("d");
    b.add("e");
    b.add("r");

    HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

    hm.put("Tomek", a);
    hm.put("KOT", b);

    for (Entry<String, ArrayList<String> m : hm.entrySet()) {

        // code to type....
    }

}

Upvotes: 0

Views: 31

Answers (1)

Ganesh chaitanya
Ganesh chaitanya

Reputation: 658

You can use the below code to print all the elements in the lists :

hm.forEach((key, arr) -> {
            arr.forEach( arrayListElement -> System.out.println(arrayListElement));
});

We are iterating through each element in map which provides us the array list element and then iterate through the list element to get the items in the list.

Upvotes: 1

Related Questions