How to find duplicate number on Integer array in Java

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-14 12:34:49 Viewed : 360

To find duplicate numbers in an integer array in Java, you can use various approaches such as using a HashSet, sorting the array, or using brute force nested loops. Here are a couple of common approaches:

1. Using HashSet: A HashSet is a collection that does not allow duplicate elements. You can iterate through the array, and for each element, check if its already present in the HashSet. If it is, then its a duplicate.

```javaimport java.util.HashSet;
import java.util.Set;

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

Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();

for (int num : array) {
}
}

System.out.println("Duplicate numbers: " + duplicates);
}
}```

2. Sorting the Array: Sorting the array and then iterating through it to find consecutive elements that are equal will help identify duplicates.

```javaimport java.util.Arrays;

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

Arrays.sort(array);

for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
System.out.println("Duplicate number: " + array[i]);
}
}
}
}```

In both approaches, the output will indicate the duplicate numbers present in the array. The first approach using a HashSet is generally more efficient for large arrays, while the second approach of sorting the array is efficient when the array is already sorted or the number of duplicates is relatively small.