I have this Map:
Map<String, List<Map<String, Integer>>> map = new HashMap<>();
I want to iterate through this Map by using the classic for loop and without using other methods such as Iterator
Thank you!
CodePudding user response:
Yes, we can do it. Wrote sample implementation below. Hope it should help.
public class TestDummy {
public static void main(String[] args) {
Map<String, Integer> temp = new HashMap<>();
temp.put("harish", 1);
List<Map<String, Integer>> tempList = new ArrayList<>();
tempList.add(temp);
Map<String, List<Map<String, Integer>>> map = new HashMap<>();
map.put("shyam", tempList);
for (Map.Entry<String, List<Map<String, Integer>>> entry : map.entrySet()) {
System.out.println("[Key] : " entry.getKey() " [Value] : " entry.getValue());
}
}
}
Output will be as:
[Key] : shyam [Value] : [{harish=1}]
CodePudding user response:
public static void main(String[] args) {
Map<String, List<Map<String, Integer>>> map = new HashMap<>();
map.put("Test", List.of(Map.of("TestValue", 1)));
map.put("Test2", List.of(Map.of("TestValue2", 2)));
Object[] entries = map.entrySet().toArray();
for (int i = 0; i < entries.length; i ) {
System.out.println(entries[i]);
}
}
