title: Counting duplicate elements in a Java String array
body: <p>I have a String array that has been randomly populated by String elements. I would like to iterate through the array and keep count of how many duplicate elements are found. I have found other answers that simply check if there is a duplicate or the position of a duplicate but not how many duplicates exist in the array.</p>
  
  <p>For example:</p>
  
  <pre><code>String [] arrayToCheck = {"A", "B", "C", "A", "B", "C"};
  </code></pre>
  
  <p>The number of duplicates found would be 3 (1 of each string is duplicated).</p>
  
  <p>I've tried many different things but can't seem to come up with code that gives me the correct answer (the number of duplicates in the array) no matter how many duplicates there are.</p>
  
  <p>Here's is what I've tried to no avail:</p>
  
  <pre><code>int numDupes = 0;
  
  for (int j = 0; j &lt; arrayToCheck.length; j++) 
       for (int k = j + 1; k &lt; arrayToCheck.length; k++) 
            if (k != j &amp;&amp; arrayToCheck[k].equals(arrayToCheck[j])) 
                numDupes++;
  </code></pre>
  
  <p>AND:</p>
  
  <pre><code>int numDupes = 0;
  
  for (String someVal : arrayToCheck) {
       for (int i = 0; i &lt; arrayToCheck.length; i++) {
            if (arrayToCheck[i].equals(someVal)) {
                numDupes++;
            }
       }
  }
  </code></pre>
  
  <p>AND:</p>
  
  <pre><code>int numDupes = 0;
  
  for(int i = 1; i &lt; arrayToCheck.length; i++) {
      if(arrayToCheck[i].equals(arrayToCheck[i-1])) {
         numDupes++;
      }
  }
  </code></pre>
  
  <p>Thanks!</p>