Java Program to count total duplicate elements in array

Java Program to count total duplicate elements in array

To count the duplicate number in array, We will be using for loop two times and perform the comparison. If value matched then increase the count otherwise not.

What is duplicate number?

Duplicate means two identical copies of same element. If a number is present two times in array we will treat this element as duplicate number.

So suppose if number is present three times in an array then we will consider it as two duplicate number.

For example:

arr = [1, 2, 3, 4, 2, 3, 4]

Output : 3 number is duplicate

arr = [1, 2, 3, 4, 2, 3, 4, 3, 4]

Output: 5 number is duplicate. (Here 3 and 4 are repeated 3 times)

Program 1: Java program to print count of duplicate element in array

import java.util.*;
class Main
{
    private static Scanner sc;
	public static void main(String[] args) {
		int size, i, j, count = 0;
		sc = new Scanner(System.in);
		System.out.println("Please Enter the Array size  : ");
		size = sc.nextInt();
		int[] arr = new int[size];
		for(i = 0; i < size; i++) 
		{
            System.out.print("Please give value for index "+ i +" : ");
            arr[i] = sc.nextInt();
        }
		for(i = 0; i < size; i++) 
		{
			for(j = i + 1; j < size; j++)
			{
				if(arr[i] == arr[j]) {
					count++;
					break;
				}
			}
		}
		System.out.println("\nThe Total Number of Duplicates  = " + count);
	}
}

Output

Please Enter the Array size  : 
5
Please give value for index 0 : 3
Please give value for index 1 : 4
Please give value for index 2 : 6
Please give value for index 3 : 2
Please give value for index 4 : 4

The Total Number of Duplicates  = 1