Write a Java Program to Count Array Duplicates with an example or how to write a program to find and count the duplicates in a given array.
In this Java count duplicate array number example, we used a while loop to iterate Dup_Count_arrr array, count duplicate items (item shown more than once), and print the total.
package ArrayPrograms; public class CountArrayDuplicates { public static void main(String[] args) { int i = 0, j, dup_count = 0; int[] Dup_Count_arr = {10, 15, 25, 10, 8, 12, 10, 15, 55, 10, 60}; while(i < Dup_Count_arr.length) { j = i + 1; while(j < Dup_Count_arr.length) { if(Dup_Count_arr[i] == Dup_Count_arr[j]) { dup_count++; break; } j++; } i++; } System.out.println("\nThe Total Number of Duplicates = " + dup_count); } }
The Total Number of Duplicates = 4
Java Program to Count Duplicates in an Array using For Loop
package ArrayPrograms; import java.util.Scanner; public class CountArrayDuplicates1 { private static Scanner sc; public static void main(String[] args) { int Size, i, j, dup_count = 0; sc = new Scanner(System.in); System.out.print("\nPlease Enter the Duplicate Array size : "); Size = sc.nextInt(); int[] Dup_Count_arr = new int[Size]; System.out.format("\nEnter Duplicate Array %d elements : ", Size); for(i = 0; i < Size; i++) { Dup_Count_arr[i] = sc.nextInt(); } for(i = 0; i < Size; i++) { for(j = i + 1; j < Size; j++) { if(Dup_Count_arr[i] == Dup_Count_arr[j]) { dup_count++; break; } } } System.out.println("\nThe Total Number of Duplicates = " + dup_count); } }
In this count duplicate array items in example, we created a separate function CountDuplicateElement to count and return duplicate count.
package ArrayPrograms; import java.util.Scanner; public class CountArrayDuplicates2 { private static Scanner sc; public static void main(String[] args) { int Size, i; sc = new Scanner(System.in); System.out.print("\nPlease Enter the Duplicate Array size : "); Size = sc.nextInt(); int[] Dup_Count_arr = new int[Size]; System.out.format("\nEnter Duplicate Array %d elements : ", Size); for(i = 0; i < Size; i++) { Dup_Count_arr[i] = sc.nextInt(); } int dup_count = CountDuplicateElement(Dup_Count_arr, Size); System.out.println("\nThe Total Number of Duplicates = " + dup_count); } public static int CountDuplicateElement(int[] Dup_Count_arr, int Size ) { int i, j, dup_count = 0; for(i = 0; i < Size; i++) { for(j = i + 1; j < Size; j++) { if(Dup_Count_arr[i] == Dup_Count_arr[j]) { dup_count++; break; } } } return dup_count; } }
Please Enter the Duplicate Array size : 11
Enter Duplicate Array 11 elements : 4 22 19 4 22 11 4 19 9 19 99
The Total Number of Duplicates = 5