In this article , we will learn , Three below things :-
1). How to Find Duplicate Element in array
2). How to find count of duplicate element in array.
3). How to remove duplicate element from array.
Note : It is very important tutorial for interview purpose.
Video :
It can be achieved by simple below algorithm :-
First create a collection.
now compare each element, within this collection
If collection have that element, than ignore else add this element to collection.
Below is Sample code :-
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class Interviewtest
{
//find the duplicate elements in the array
int count;
public static void main(String args[])
{
int arr[] = {4, 2, 2, 4, 55, 6, 99, 55};
AtomicInteger count = new AtomicInteger(1);
Set newarray = new HashSet();
for(int i =0; i<arr.length; i++)
{
if(newarray.contains(arr[i]))
{
int x = count.getAndIncrement();
//System.out.println("Element"+ " " + arr[i] + " " + x);
}
else
{
newarray.add(arr[i]);
}
for(int j =i+1; j<arr.length; j++)
{
if(arr[i]==arr[j])
{
System.out.println("Duplicate element is:->" +" "+arr[i]);
}
}
}
System.out.println(newarray);
g();
h();
}
public static void g()
{
String arr[] = new String[]{"chandan", "adhiraj", "Tina", "Cathy", "chandan", "adhiraj"};
Set duplicate = new HashSet<>();
Set nonduplicate = new HashSet<>();
for(String srting : arr)
{
/*if(!nonduplicate.contains(srting))
{
nonduplicate.add(srting);
}
else
{
duplicate.add(srting);
}*/
if(nonduplicate.contains(srting))
{
duplicate.add(srting);
}
else
{
nonduplicate.add(srting);
}
}
System.out.println(duplicate);
System.out.println(nonduplicate);
}
public static void h()
{
int arr[] = {4, 2, 2, 4, 55, 6, 99, 55};
for(int i =0; i<arr.length; i++)
{
int t = 1;
for(int j =i+1; j<arr.length; j++)
{
if(arr[i]==arr[j])
{
t = t+1;
}
}
System.out.println("Element" + " " + arr[i] + " " + "occurs" + " " + t);
}
}
}