DEV Community

realNameHidden
realNameHidden

Posted on

2 1 1 1 1

Write a Java program to find duplicate elements in an array

for explanation watch video

Find Duplicates using HashSet

import java.util.HashSet;

public class FindDuplicates {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 2, 6, 4, 7, 8, 3};

        findDuplicates(array);
    }

    public static void findDuplicates(int[] array) {
        HashSet<Integer> set = new HashSet<>();
        HashSet<Integer> duplicates = new HashSet<>();

        for (int num : array) {
            if (!set.add(num)) { // if add() returns false, num is a duplicate
                duplicates.add(num);
            }
        }

        if (duplicates.isEmpty()) {
            System.out.println("No duplicates found");
        } else {
            System.out.println("Duplicate elements: " + duplicates);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Using For loop

public class FindDuplicatesUsingLoop {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 2, 6, 4, 7, 8, 3};

        findDuplicates(array);
    }

    public static void findDuplicates(int[] array) {
        boolean hasDuplicates = false;

        System.out.print("Duplicate elements: ");
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] == array[j]) {
                    System.out.print(array[i] + " ");
                    hasDuplicates = true;
                    break; // Avoids printing the same duplicate multiple times
                }
            }
        }

        if (!hasDuplicates) {
            System.out.print("No duplicates found");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode
👋 One last chance before you go!

It takes one minute to join DEV and is worth it for your career.

You get 3x the value by signing in instead of lurking

Get started

Community matters

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay