TL;DR:
var merged = Stream.of(map1, map2, ..., mapN).reduce(new HashMap<>(), (a, b) -> {
a.putAll(b);
return a;
});
您可以使用reduce 将Map<String, Map<String, String>> 元素流合并为一个:
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);
}
}
输出:
{name={property=value}, name2={property=value}}
{name={property=value}, name2={property=value}}
但请注意,这些解决方案假定键(name 和 name2)是唯一的,否则重复键会使映射条目相互覆盖。
具有更现代语法的相同逻辑:
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);
}
}