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. If frequency of any element is id more than 1, then it is a duplicate element otherwise it is a unique element.
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 to store the frequency of elements of inputArray.
  • 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


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.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){
                // 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 + " ");

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

Recommended Posts
Java Program to Find Sum of Elements of an Array
Java Program to Search an Element in an Array using Linear Search
Java Program to Find Average of all Array Elements
Java Program to Merge Two Sorted Arrays
Java Program to Insert an Element in Array at Given Position
Java Program to Find Largest and Smallest Number in an Array
Java Program to Check Whether two Strings are Equal or Not
Java Program to Concatenate Two Strings
Java Program to Find Count of Each Character in a String
Java Program to Find Length of a String
Java Program to Reverse Sequence of Words of a Sentence
All Java Programs