TL;DR:
var merged = Stream.of(map1, map2, ..., mapN).reduce(new HashMap<>(), (a, b) -> {
a.putAll(b);
return a;
});
You can use reduce to combine a stream of Map<String, Map<String, String>> elements into one:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
alternative1();
alternative2();
}
// Use reduce without an initial identity value
public static void alternative1() {
Map<String, Map<String, String>> m1 = new HashMap<>();
m1.put("name", Map.of("property", "value"));
Map<String, Map<String, String>> m2 = new HashMap<>();
m2.put("name2", Map.of("property", "value"));
Stream<Map<String, Map<String, String>>> mapStream = Stream.of(m1, m2);
Map<String, Map<String, String>> m3 = mapStream.reduce((a, b) -> {
Map<String, Map<String, String>> temp = new HashMap<>();
temp.putAll(a);
temp.putAll(b);
return temp;
}).orElseThrow();
System.out.println(m3);
}
// Use reduce with an initial empty map as the identity value
public static void alternative2() {
Map<String, Map<String, String>> m1 = new HashMap<>();
m1.put("name", Map.of("property", "value"));
Map<String, Map<String, String>> m2 = new HashMap<>();
m2.put("name2", Map.of("property", "value"));
Stream<Map<String, Map<String, String>>> mapStream = Stream.of(m1, m2);
Map<String, Map<String, String>> m3 = mapStream.reduce(new HashMap<>(), (a, b) -> {
a.putAll(b);
return a;
});
System.out.println(m3);
}
}
Output:
{name={property=value}, name2={property=value}}
{name={property=value}, name2={property=value}}
But beware that these solutions assume keys (name and name2) are unique, otherwise duplicate keys would make map entries overwrite each other.
The same logic with a more modern syntax:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
alternative1();
alternative2();
}
// Use reduce without an initial identity value
public static void alternative1() {
var m1 = Map.of("name", Map.of("property", "value"));
var m2 = Map.of("name2", Map.of("property", "value"));
var m3 = Stream.of(m1, m2).reduce((a, b) -> {
var temp = new HashMap<String, Map<String, String>>();
temp.putAll(a);
temp.putAll(b);
return temp;
}).orElseThrow();
System.out.println(m3);
}
// Use reduce with an initial empty map as the identity value
public static void alternative2() {
var m1 = Map.of("name", Map.of("property", "value"));
var m2 = Map.of("name2", Map.of("property", "value"));
var m3 = Stream.of(m1, m2).reduce(new HashMap<>(), (a, b) -> {
a.putAll(b);
return a;
});
System.out.println(m3);
}
}
getInfoStreamand whatsomeObjectlooks like, pleasegetInfoStreamwhich is returning aStream<Map<>>and not evenStream<Map.Entry>s.