import org.json.JSONObject;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MergeMaps {
public static void main(String[] args) {
// 假设有四个值类型为JSONObject的map
Map<String, JSONObject> map1 = Map.of(
"key1", new JSONObject("{\"a\": 1, \"b\": 2}"),
"key2", new JSONObject("{\"c\": 3}")
);
Map<String, JSONObject> map2 = Map.of(
"key1", new JSONObject("{\"c\": 4, \"d\": 5}"),
"key3", new JSONObject("{\"e\": 6}")
);
Map<String, JSONObject> map3 = Map.of(
"key2", new JSONObject("{\"d\": 7}"),
"key4", new JSONObject("{\"f\": 8}")
);
Map<String, JSONObject> map4 = Map.of(
"key1", new JSONObject("{\"e\": 9}"),
"key4", new JSONObject("{\"g\": 10}")
);
// 合并四个map
Map<String, JSONObject> mergedMap = Stream.of(map1, map2, map3, map4)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(json1, json2) -> {
// 如果键相同,将两个JSONObject合并到一个JSONObject中
JSONObject mergedJson = new JSONObject();
json1.keySet().forEach(key -> mergedJson.put(key, json1.get(key)));
json2.keySet().forEach(key -> mergedJson.put(key, json2.get(key)));
return mergedJson;
}
));
// 输出合并后的map
mergedMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Java合并多个值为JSONObject类型Map,键相同时,将值合并到一个JSONObject中
于 2023-06-13 15:41:26 首次发布