how to find if there is a duplicate entry in an array of integers java code example
Example 1: java find duplicates in array
package dto;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class DuplicatesInArray{
public static void main(String args[]) {
String[] names = { "Java", "JavaScript", "Python", "C", "Ruby", "Java" };
System.out.println("Finding duplicate elements in array using brute force method");
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i].equals(names[j]) ) {
}
}
}
System.out.println("Duplicate elements from array using HashSet data structure");
Set<String> store = new HashSet<>();
for (String name : names) {
if (store.add(name) == false) {
System.out.println("found a duplicate element in array : "
+ name);
}
}
System.out.println("Duplicate elements from array using hash table");
Map<String, Integer> nameAndCount = new HashMap<>();
for (String name : names) {
Integer count = nameAndCount.get(name);
if (count == null) {
nameAndCount.put(name, 1);
} else {
nameAndCount.put(name, ++count);
}
}
Set<Entry<String, Integer>> entrySet = nameAndCount.entrySet();
for (Entry<String, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.println("Duplicate element from array : "
+ entry.getKey());
}
}
}
}
Output :
Finding duplicate elements in array using brute force method
Duplicate elements from array using HashSet data structure
found a duplicate element in array : Java
Duplicate elements from array using hash table
Duplicate element from array : Java
Example 2: find duplicate elements in array in java
public static void findDuplicateArray(int [] array)
{
int size = array.length;
int [] countFrequency = new int[size];
for(int i = 0; i < size; i++)
{
countFrequency[i] = -1;
}
int count = 1;
for(int i = 0; i < size; i++)
{
if(countFrequency[i] != 0)
{
for(int j = i+1; j < size; j++)
{
if(array[i] == array[j])
{
count++;
countFrequency[j]= 0;
}
}
countFrequency[i] = count;
}
count = 1;
}
System.out.println("array without duplicate elements");
for(int i = 0; i < array.length; i++)
{
if(countFrequency[i] >= 1)
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("duplicate elements in array");
for(int i = 0; i < array.length; i++)
{
if(countFrequency[i]/2 >= 1)
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("number of duplicate elements");
count = 0;
for(int i = 0; i < array.length; i++)
{
if(countFrequency[i]/2 >= 1)
count++;
}
System.out.print(count);
System.out.println();
System.out.println("numbers of pair of dulicate with repeatation");
count = 0;
for(int i = 0; i < array.length; i++)
{
if(countFrequency[i] >= 2)
{
int div = countFrequency[i]/2;
count+=div;
}
}
System.out.println(count);
int [] array3 = new int [array.length];
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < countFrequency[i]; j++)
{
array3[i]= array[i];
}
}
}