5

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.

Simon
  • 19,658
  • 27
  • 149
  • 217
  • 1
    Java or JavaScript? (asking 'cuz Java <> JavaScript) – blurfus Sep 29 '15 at 18:02
  • Java. Its in the heading of the question. – Simon Sep 29 '15 at 18:05
  • Oh, I know but the first answer (don't see it now) threw me off because it was providing JS code so I wanted to make sure – blurfus Sep 29 '15 at 18:15
  • I don't think the guy read the question or saw the tags on the question - i see he deleted it now. – Simon Sep 29 '15 at 18:17
  • Is there any possibilities that the keys of the first array may be found in the second array? (other than `"id"`, of course) – blurfus Sep 29 '15 at 18:19
  • You mean would "acceptsCard" be found in both array? Nope. The arrays are received from two different servers and each is giving their own unique json properties -- the only think that is the same is the "id" – Simon Sep 29 '15 at 18:21
  • Then try: http://stackoverflow.com/questions/19566081/what-is-the-best-way-to-combine-merge-2-jsonobjects or http://stackoverflow.com/questions/2403132/concat-multiple-jsonobjects – blurfus Sep 29 '15 at 18:47

1 Answers1

3

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.

Community
  • 1
  • 1
ctrlc-root
  • 1,049
  • 1
  • 15
  • 22
  • Not sure I understand the code here - maybe you can elaborate. You are creating a for loop on the keys in the object but there is only 1 key in the object call "id" so you can't for loop against that. Also hashmap has no set method... – Simon Sep 29 '15 at 18:15
  • @Simon whoops, that was a syntax error, and I just fixed it and added a line to illustrate getting the merged objects out of the map. the code basically iterates over all the objects from both lists and merges their properties into a single JSONObject `existing` based on the `id` key. that object is stored in a `Map` so retrieving it using it's `id` is fast. does that make sense? – ctrlc-root Sep 29 '15 at 18:19
  • @Simon regarding the for loop, it doesn't matter if the object has 0 or more keys, the `JSONObject.keys()` function will return an `Iterator` over a list of them (that list may just happen to be empty or only contain one item). Like I said, I haven't programmed in Java in a while, and you may actually need to modify that loop to explicitly work with the returned `Iterator` object, not sure if you can use `for each` there. – ctrlc-root Sep 29 '15 at 18:23
  • I need to go think about this a little but what you have done there makes quite a lot of sense. I will need to test it out first and will get back to you. – Simon Sep 29 '15 at 18:29
  • Thanks - it is working but i realized i might need to take a step back and combine at the pojo level instead. I will post a new question shortly. – Simon Sep 30 '15 at 17:04