Find duplicate elements in an array

This Java code example shows how to find duplicates in an array. For this example we are using an int[] array as our input to process.
Every number in the array is stored in a Map collection object as the key, along with a value that tells how many times that particular number exist in the array. This is done by looping through the array and checking the map for that number. If it exists in the map the value is incremented by one. If not it is added to the map with a value of 1.

Since we want the numbers sorted in the output we’re using a TreeMap which by default sorts its content. To output the result we use an Iterator to loop through the keys in the Map and print it out along with the corresponding value (number of occurrences).

The code for this example is shown below:

The output from the code will look like this:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?