Review Hướng Dẫn Map Mới Nhất
This Java program shows how to iterate a HashMap that contains arraylists of String.
In the Java program to iterate a HashMap containing ArrayLists there is a method getMap() where 3 lists are created and stored in the HashMap.
First you need to iterate the HashMap, though there are several ways to iterate over a HashMap, but here I have used the for-each loop for iterating the created HashMap. Each Map.Entry object is a key-value pair where value is the ArrayList stored with the given key. That’s the list retrieved using listEntry.getValue() method.
In the second for-each loop List that is retrieved using listEntry.getValue() is iterated and the elements that are in the list are displayed.
Java Program to Iterate HashMap of ArrayLists
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapLoop
public static void main(String[] args)
MapLoop mapLoop = new MapLoop();
Mapvàlt;String, Listvàlt;Stringvàgt;> cityMap = mapLoop.getMap();
int i = 0;
// iterating over a map
for(Map.Entryvàlt;String, Listvàlt;Stringvàgt;> listEntry : cityMap.entrySet())
System.out.println(“Iterating list number – ” + ++i);
// iterating over a list
for(String cityName : listEntry.getValue())
System.out.println(“City – ” + cityName);
/**
* A method to create a list and store it in a Map
* @return
*/
private Mapvàlt;String, Listvàlt;Stringvàgt;> getMap()
Mapvàlt;String, Listvàlt;Stringvàgt;> cityMap = new HashMapvàlt;String, Listvàlt;Stringvàgt;>();
// First List
Listvàlt;Stringvàgt; temp = new ArrayListvàlt;Stringvàgt;();
temp.add(“Delhi”);
temp.add(“Mumbai”);
// Putting first list in the map
cityMap.put(“1”, temp);
// Second List
temp = new ArrayListvàlt;Stringvàgt;();
temp.add(“Hyderabad”);
temp.add(“Bangalore”);
// Putting second list in the map
cityMap.put(“2”, temp);
// Third List
temp = new ArrayListvàlt;Stringvàgt;();
temp.add(“Kolkata”);
temp.add(“Chennai”);
// Putting third list in the map
cityMap.put(“3”, temp);
return cityMap;
OutputIterating list number – 1
City – Delhi
City – Mumbai
Iterating list number – 2
City – Hyderabad
City – Bangalore
Iterating list number – 3
City – Kolkata
City – Chennai
That’s all for this topic How to iterate a Hash map of arraylists of String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
Review Map ?
Bạn vừa đọc nội dung bài viết Với Một số hướng dẫn một cách rõ ràng hơn về đoạn Clip Map mới nhất , Heros đang tìm một số trong những ShareLink Download Map miễn phí.
Thảo Luận thắc mắc về Map
Nếu sau khoản thời hạn đọc nội dung bài viết Map vẫn chưa hiểu thì trọn vẹn có thể lại phản hồi ở cuối bài để Ad lý giải và hướng dẫn lại nha
#Map