If you're ok with overriding the keys, you can just merge the Map
s into a single map with collect
, even without flatMap
s:
public static void main(String[] args) throws Exception {
final List<Map<String, String>> cavia = new ArrayList<Map<String, String>>() {{
add(new HashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
put("key3", "value3");
put("key4", "value4");
}});
add(new HashMap<String, String>() {{
put("key5", "value5");
put("key6", "value6");
put("key7", "value7");
put("key8", "value8");
}});
add(new HashMap<String, String>() {{
put("key1", "value1!");
put("key5", "value5!");
}});
}};
cavia
.stream()
.collect(HashMap::new, HashMap::putAll, HashMap::putAll)
.entrySet()
.forEach(System.out::println);
}
Will output:
key1=value1!
key2=value2
key5=value5!
key6=value6
key3=value3
key4=value4
key7=value7
key8=value8