Use Collector to merge multiple JSON objects into onejava/data/merge-json-objectTurn Stream<JsonObject> to single JsonObject
1static Collector<JsonElement, ?, JsonObject> collectAsJsonObject() {
2 return Collector.of(
3 JsonObject::new,
4 (obj, element) -> {
5 if (element.isJsonObject()) {
6 for (Map.Entry<String, JsonElement> key : element.getAsJsonObject().entrySet()) {
7 obj.add(key.getKey(), key.getValue());
8 }
9 }
10 },
11 (obj1, obj2) -> {
12 for (Map.Entry<String, JsonElement> key : obj2.entrySet()) {
13 obj1.add(key.getKey(), key.getValue());
14 }
15 return obj1;
16 }
17 );
18}Disclaimer
The code snippet is provided for reference and learning purposes only. Users should use it at their own risk. I, along with the related developers, shall not be held responsible for any direct or indirect losses caused by the use of this code snippet, including but not limited to data loss, computer malfunctions, program errors, etc.