Find duplicate elements in array in java – Java Program to Find Duplicate Elements in an Array

Find duplicate elements in array in java: Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Java Program to Find Duplicate Elements in an Array

    • Write a program in Java to find duplicate elements in an integer array.
    • Algorithm to find duplicate numbers in an integer array.

Given an array of integers(which may contains duplicate elements), we have to print all duplicate elements of array once. To find duplicate elements, we will count the frequency of each elements of array and store it in a Map<integer, integer=””>. If frequency of any element is id more than 1, then it is a duplicate element otherwise it is a unique element.</integer,>

Input Array
1 7 3 2 1 6 4 2
Duplicate Elements
1 2

Algorithm to find duplicate elements in Array

  • Declare an integer array “inputArray” for storing input array elements.
  • Declare a Map<integer, integer=””> to store the frequency of elements of inputArray.</integer,>
  • Using for-each loop, traverse input array and for each element check whether element exists in Map or not.
  • If present in map, increment it’s count, other wise create a new entry in Map with count as 1.
  • For each key-value entry in Map, check whether value is > 1, If true then corresponding key is a duplicate element otherwise unique element.

Java program to find duplicate elements

Java program to find duplicate elements

package com.tcc.java.programs;
 
import java.util.*;
 
public class DuplicateElements {
    public static void main(String args[]) {
        int count, i;
        int[] inputArray = new int[500];
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        Scanner in = new Scanner(System.in);
   
        System.out.println("Enter number of elements");
        count = in.nextInt();
        System.out.println("Enter " + count + " elements");
        for(i = 0; i < count; i++) {
            inputArray[i] = in.nextInt();
        }
  
        // Count frequency of elements in array
        for(Integer val: inputArray){
            if(map.containsKey(val)){
                // Increment counter
                map.put(val, map.get(val)+1);
            } else {
                map.put(val, 1);
            }
        }
  
        // Check for duplicate element
        System.out.println("Duplicate Elements\n");
        Set<Integer> keys = map.keySet();
        for (Integer key : keys){
            if(map.get(key) > 1){
                System.out.print(key + " ");
            }
        }
 
    }
}

Output

Enter number of elements
6
Enter 6 elements
3 6 2 3 1 1
Duplicate Elements
1 3