Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to find duplicate elements in Array In Java

In this post I am sharing how to detect Duplicate values in array using Java Programming. This is one the frequently asked programming interview question in technical interview. I am showing two methods to find duplicate elements in array. Interviewer wants to know your logical thinking how could solve  problems easy way. So, be ready to write programming logic's in efficient and effective manner.

The following are the steps how to Detect Duplicate Values in array:


  • First you need to create and initialize input array
  • Create an empty set and name it as non duplicate set
  • create an empty set and name it as duplicate set
  • Now iterate through each element in the array and check whether non-duplicates contains the element. If it is present add it to the duplicate set
  • If it is not present add it to non duplicate set
  • Finally Print the elements in duplicate set
Method 1:

Now let us see the program to find print duplicate elements in the array

import java.util.HashSet;
import java.util.Set;
class DuplicateElementsArray
{
public static void main(String args[])
{
String duplicate[]=new String[]{"apple","grapes","banana","apple"};
Set nonDuplicatesSet=new HashSet();
Set duplicateSet=new HashSet();
for(String s:duplicate)
{
if(!nonDuplicatesSet.contains(s))
{
nonDuplicatesSet.add(s);
}
else
{
duplicateSet.add(s);
}
}
System.out.println(duplicateSet);
}

Output:


Method 2:


import java.util.HashSet;
import java.util.Set;

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

Setset=new HashSet();
for(int i=0;i
{
if(set.add(arr[i])==false)
{
System.out.println("Duplicate values:"+arr[i]);
}


Output:



This post first appeared on Learnprogramingbyluckysir, please read the originial post: here

Share the post

How to find duplicate elements in Array In Java

×

Subscribe to Learnprogramingbyluckysir

Get updates delivered right to your inbox!

Thank you for your subscription

×