Java 8+
For singleton maps
Use groupingBy to separate by key and then mapping to get the value of your singleton map
Map<String, List<String>> res =
list.stream()
.map(map -> map.entrySet().iterator().next())
.collect(Collectors.groupingBy(
entry -> entry.getKey(),
Collectors.mapping(
entry -> entry.getValue(),
Collectors.toList()
)
)
);
For maps with multiple entries
You do the same as above, but flatMap to get all the entries in a single 1-D stream
Map<String, List<String>> res =
list.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(
entry -> entry.getKey(),
Collectors.mapping(
entry -> entry.getValue(),
Collectors.toList()
)
)
);
Pre-Java 8
For maps with multiple entries
You'll have to iterate through each map in the list, and then through the entries of each map. For each entry, check if the key's already there, and if so, add the value to the list associated with that key. If the key's not in the result map, then create a new list there.
Map<String, List<String>> map = new HashMap<>();
for (Map<String, String> m : list) {
for (Map.Entry<String, String> e : m.entrySet()) {
String key = e.getKey();
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(e.getValue());
}
}
For singleton maps
For each map in your original list, you find the first entry, and then you do the same as above: add that entry's value to the list that the entry's key maps to, and before that, add a new List to the map if the key doesn't exist there already.
Map<String, List<String>> map = new HashMap<>();
for (Map<String, String> m : list) {
Map.Entry<String, String> e = m.entrySet().iterator().next();
String key = e.getKey();
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(e.getValue());
}