How to Iterate a List of Maps in Java
In this blog post, we will explore different techniques to iterate through a list of maps in Java, providing you with the knowledge and tools to efficiently work with such data structures.
Let’s assume we have the following list of maps:
List<Map<String, Object>> listOfMaps = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "John");
map1.put("age", 30);
listOfMaps.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "Alice");
map2.put("age", 25);
listOfMaps.add(map2);
Using Map.entrySet()
The entrySet()
method of the Map
interface returns a set view of the map’s key-value pairs as Map.Entry
objects. You can then iterate through this set and access the key and value of each entry.
for (Map<String, Object> map : listOfMaps) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.format("%s: %s\n", key, value);
}
}
Output:
name: John
age: 30
name: Alice
age: 25
Using Map.keySet() and Map.get()
The keySet()
method of the Map
interface returns a set containing all the keys in the map. You can then iterate through this set, and for each key, fetch the corresponding value using the get()
method.
for (Map<String, Object> map : listOfMaps) {
for (String key : map.keySet()) {
Object value = map.get(key);
System.out.format("%s: %s\n", key, value);
}
}
Output:
name: John
age: 30
name: Alice
age: 25
Using Streams and flatMap (Java 8 and above)
With Java 8 and beyond, you can use the Stream API and the flatMap
method to iterate through the list of maps’ key-value pairs in a more functional way.
listOfMaps.stream()
.flatMap(map -> map.entrySet().stream())
.forEach(entry -> {
String key = entry.getKey();
Object value = entry.getValue();
System.out.format("%s: %s\n", key, value);
});
Output:
name: John
age: 30
name: Alice
age: 25
These approaches will allow you to dynamically access the keys and values of the maps within the list without knowing their names beforehand. Choose the one that best fits your coding style and requirements. Happy coding!