Java Program to Count the duplicate numbers in an array

In this tutorial, you will learn how do you count the number of occurrences of a number in an array java.

How our program will behave?

Our program will take an array as an input.

And on the basis of inputs it will perform some operation to count the occurrence of all numbers and then print the duplicate number count.

Java Program to Count the duplicate numbers in an array

Program 1: Using HashMap

import java.util.*;

public class CountDuplicate {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array: ");
        int n = sc.nextInt();
        int array[] = new int[n];
        Map<Integer, Integer> counts = new HashMap<>();
        System.out.println("Please Enter array elements ");
        for(int i = 0; i < n; i++) {
            array[i] = sc.nextInt();
            counts.put(array[i], counts.getOrDefault(array[i], 0) + 1);
        }
        int duplicateCount = 0;
        System.out.println("Duplicate values and their counts:");
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " occurs " + entry.getValue() + " times");
                duplicateCount++;
            }
        }
        
        System.out.println("Total duplicate numbers are " + duplicateCount);
    }
}

Output:

Enter the size of array: 
6
Please Enter array elements 
1
2
3
1
3
1
Duplicate values and their counts:
1 occurs 3 times
3 occurs 2 times
Total duplicate numbers are 2

Program 2: Using Arrays.sort()

import java.util.*;

public class CountDuplicate {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array: ");
        int n = sc.nextInt();
        int array[] = new int[n];
        Map<Integer, Integer> counts = new HashMap<>();
        System.out.println("Please Enter array elements ");
        for(int i = 0; i < n; i++) {
            array[i] = sc.nextInt();
        }
        Arrays.sort(array);
        Set<Integer> duplicates = new HashSet<>();
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] == array[i + 1]) {
                duplicates.add(array[i]);
            }
        }
        
        System.out.println("Duplicate numbers:");
        for (int num : duplicates) {
            System.out.println(num);
        }
        
        System.out.println("Total count of duplicate numbers are " + duplicates.size());
    }
}

Output

Enter the size of array: 
7
Please Enter array elements 
1
1
2
3
4
4
5
Duplicate numbers:
1
4
Total count of duplicate numbers are 2

Leave a Comment