how to count duplicate elements in array in java

Semiron :

I have an array of integers like = 3,1,2,3,1 ; and I just want to count how many duplicates this array has. for example this array has 4 duplicates now. input is the array and the output will be number of duplicating elements. is there any methods or classes for it? can you help me to implement my own? Note : I'm not looking for number of occurrence of a specified element. I just want to know how many duplicates this array has at all. for example I said it has 4 duplicates for the mentioned array. 2 of them are "3" and 2 of them are "1"!

Gtomika :

Well a map can be used to store then numbers and the amount of times they appeared:

Map<Integer,Integer> map = new HashMap<>();
for(int i: numbers) { //suppose you have the numbers in 'numbers' array
   if(map.containsKey(i) { //this number is in the map already
      map.put(i, map.get(i)+1);
   } else { //we didnt see this number before
      map.put(i, 1);
   }
}

//now we loop the map to sum the repeating numbers
int sum = 0;
for(int amount: map.values()) {
   if(amount > 1) sum += amount;
}

An advantage of this method is that you know exactly how many of each numbers the are in the array. You may need that info later.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related