Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect duplicate values in primitive Java array

I want to detect duplicate values in a Java array. For example:

int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };

How could I get the specific duplicated entry and how many times it occurs?

like image 893
Mohit Deshpande Avatar asked Nov 29 '22 04:11

Mohit Deshpande


1 Answers

I'll have a Map<Integer, Integer> where the first integer is the value of the number that occurs in the array and the second integer is the count (number of occurrence).

  • Run through the array.length in a loop
  • for each item in the array, do a map.containsKey(array[i]). If there exists a number in a map, increment that number (something like map.put(array[i], map.get(array[i]) + 1). Otherwise, create a new entry in a map (e.g map.put(array[i], 1).
  • Finally, iterate through the map and retrieve all keys where value is greater than 1.
like image 166
Buhake Sindi Avatar answered Dec 15 '22 02:12

Buhake Sindi