title: Java: Merging two json objects together with primary key
body: <p>Lets say I have two arrays of JSONObjects in memory and each object has a key that is similar in both arrays:</p>
  
  <p><strong>Array 1</strong></p>
  
  <pre><code>[
    {
      "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...} ]
  </code></pre>
  
  <p><strong>Array 2</strong></p>
  
  <pre><code>[
    {
      "acceptsCard": "true"
      "id": "1A"
    },
    {
      "acceptsCard": "false"
      "id": "2A"
    },
    {
      "acceptsCard": "false"
      "id": "3A"
    }, {other JSON Objects...} ]
  </code></pre>
  
  <p>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:</p>
  
  <p><strong>MERGED ARRAY (Result)</strong></p>
  
  <pre><code>  [
        {
          "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...} ]
  </code></pre>
  
  <p>How can I do this efficiently?</p>
  
  <p>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.</p>