Write a java program to find and output all duplicates in the array.

Example:

So we need to output all those elements in the array which has appeared more than once in the array. For this we need to count the frequency of each element and store it into the HashMap.

After that we will loop through all the key value pairs of the HashMap and will output those whose count or frequency is more than 1.

Output

The getOrDefault() method of HashMap class returns 0 as default value if the passed key is not present in the hashMap or else it will return its corresponding value.

So using put() method we are updating the previous count value of each array element in the HashMap.

We could also have use another array to store count of the corresponding array element but for that we would had to explicitly determine how large the array should be and in way it is same like implementing the mapping of array element and its counts.

That’s all we need to do in order to find duplicates in the array using Java. If you have any doubts or suggestion then comment below.

Leave a Reply

Close Menu