Lets say I have two arrays of JSONObjects in memory and each object has a key that is similar in both arrays:
Array 1
[
{
"name": "Big Melons Co.",
"location": "Inner City Dubai"
"id": "1A"
},
{
"name": "Pear Flavored Juices Ltd",
"location": "Seychelles"
"id": "2A"
},
{
"name": "Squeeze My Lemons LLC",
"location": "UK"
"id": "3A"
}, {other JSON Objects...} ]
Array 2
[
{
"acceptsCard": "true"
"id": "1A"
},
{
"acceptsCard": "false"
"id": "2A"
},
{
"acceptsCard": "false"
"id": "3A"
}, {other JSON Objects...} ]
Now, I want to merge the two arrays together based on the primary key of "id" so they become one on my server side and then send the results back to my frontend - the resulting arraylist of objects should look like this:
MERGED ARRAY (Result)
[
{
"name": "Great Juice Co.",
"location": "Inner City Dubai"
"acceptsCard": "true"
"id": "1A"
},
{
"name": "Pear Flavored Juices Ltd",
"location": "Seychelles"
"acceptsCard": "false"
"id": "2A"
},
{
"name": "Squeeze My Lemons LLC",
"location": "UK"
"acceptsCard": "false"
"id": "3A"
}, {other JSON Objects...} ]
How can I do this efficiently?
I can think of one highly inefficient way to do this (I'm dreading implementing this) - I would loop though each item in either array 1 or 2 and use the equal() method for the string in the "id" field to see whether the two matches. If they match, I would create a new JSONObject to contain both the fields from array 1 and 2.
My Java is a little rusty but I would use a map.
List<JSONObject> objectsA = ... ;
List<JSONObject> objectsB = ... ;
Map entries = new HashMap<String, JSONObject>();
List<JSONObject> allObjects = new ArrayList<JSONObject>();
allObjects.addAll(objectsA);
allObjects.addAll(objectsB);
for (JSONObject obj: allObjects) {
String key = obj.getString("id");
JSONObject existing = entries.get(key);
if (existing == null) {
existing = new JSONObject();
entries.put(key, existing);
}
for (String subKey : obj.keys()) {
existing.put(subKey, obj.get(subKey));
}
}
List<JSONObject> merged = entries.values();
This is more efficient than two nested loops and there's still room for improvement.
EDIT: References to external documentation and related answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With