Find Duplicate Elements in Array

Find Duplicate Elements in Array: In this blog post, we will talk about one of the very famous interview questions, whether you are a refresher or an experienced one. That Java program finds or duplicates elements from the array.

Different Ways to Find Duplicate Elements in an Array

There are various ways of doing it:

  • The simple typical mechanism is brute force; we can use that right, write two for loops, and then compare every element one by one.
  • We can do this by using the HashSet collection’s help because we know that HashSet stores the unique values, so we can also use the hash set.
  • The third one is that we can use a HashMap where we will store the value in the form of key and value pair format, and then we will keep counting the key, and if the value is greater than one, in that case, that element is duplicate.

The above 3 ways are the standard ways of doing it, but if you consider, there are other ways also using Java streams. Here are the different ways:

  • Java Streams Using Set & Filter
  • Java Streams Using Group By
  • Java Streams Using Frequency
Post Type:Java Programs Tutorial
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Find Duplicate Elements in an Array Using the Brute Force Technique

Let’s talk about the first one, which is a typical form of brute force. It is a typical example of finding duplicate elements in an array.

Let’s take an example of the String array. Suppose the array is looking something like the below:

String arrayElements[] = {“Testing”, “Manual Testing”,”Java”, “Automation Testing”,”Software Testing”,”Java”,”Testing”};

If you notice, the array, Testing, and Java display twice, whereas the other values are unique. So, we have to find the duplicate element from this particular array using the brute force mechanism.

package com.softwaretestingo.interviewprograms;
public class FindDuplicateElementFromArray1 
{
	public static void main(String[] args) 
	{
		String arrayElements[] = {"Testing","Manual Testing", "Java","Automation Testing", 
                                                          "Software Testing","Java", "Testing"};
		System.out.println("****Brute Force Technique ****");
		for(int i=0;i<arrayElements.length;i++)
		{
			for(int j=i+1;j<arrayElements.length;j++)
			{
				if(arrayElements[i].equals(arrayElements[j]))
				{
					System.out.println(arrayElements[i]);
				}
			}
		}
	}
}

Find Duplicate Elements in an Array Using HashSet

Now, let’s discuss the second method, using the HashSet collection interface. Let’s see how we can find duplicate elements from the array with the HashSet. For this example, we are also using the same String array.

package com.softwaretestingo.interviewprograms;
import java.util.HashSet;
import java.util.Set;
public class FindDuplicateElementFromArray2 
{
	public static void main(String[] args) 
	{
		String arrayElements[] = {"Testing","Manual Testing", "Java","Automation Testing", 
                                                          "Software Testing","Java", "Testing"};
		System.out.println("********* hash set ***********");
		Set<String>data=new HashSet<String>();
		for(String ele1: arrayElements)
		{
			if(data.add(ele1)== false)
			{
				System.out.println(ele1);

			}
		}
	}
}

Find Duplicate Elements in Array Using HashMap

package com.softwaretestingo.interviewprograms;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class FindDuplicateElementFromArray3 
{
	public static void main(String[] args) 
	{
		String arrayElements[] = {"Testing","Manual Testing", "Java","Automation Testing", 
                                                          "Software Testing","Java", "Testing"};
		System.out.println("************ hash map **************");
		Map<String, Integer>arrayMap=new HashMap<String, Integer>();
		for(String e: arrayElements)
		{
			Integer count = arrayMap.get(e);
			if(count == null)
			{
				arrayMap.put(e,1);
			}
			else
			{
				arrayMap.put(e, ++ count);
			}
		}

		// print all the duplicate elements:
		Set<Entry<String,Integer>> entrySet=arrayMap.entrySet();
		for(Entry<String,Integer> entry : entrySet)
		{
			if(entry.getValue()>1)
			{
				System.out.println(entry.getKey());
			}
		}
	}
}

Find Duplicate Elements in an Array Using Java Streams Set & Filter

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class FindDuplicateElementFromArray4 
{
	public static void main(String[] args) 
	{
		String arrayElements[] = {"Testing","Manual Testing", "Java","Automation Testing", 
                                                           "Software Testing","Java", "Testing"};
		System.out.println("********* Streams!|***********");
		Set<String>dataSet=new HashSet<String>();
		Set<String>dupSet=Arrays.asList(arrayElements).
				stream().filter(e-> !dataSet.add(e)).
				collect(Collectors.toSet());
		System.out.println(dupSet);
	}
}

Find Duplicate Elements in an Array Using Java Streams Group By

package com.softwaretestingo.interviewprograms;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FindDuplicateElementFromArray5 
{
	public static void main(String[] args) 
	{
		String arrayElements[] = {"Testing","Manual Testing", "Java","Automation Testing", 
                                                           "Software Testing","Java", "Testing"};
		System.out.println("********** Streams grouping by **********");
		Set<String> eleset = Arrays.asList(arrayElements).stream().
				collect(Collectors.groupingBy(Function.identity(),Collectors.counting())).
				entrySet().stream().
                                filter(e -> e.getValue()>1).map(Map.Entry::getKey).collect(Collectors.toSet());
		
		System.out.println(eleset);
	}
}

Find Duplicate Elements in Array Using Java Streams Frequency

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class FindDuplicateElementFromArray6 
{
	public static void main(String[] args) 
	{
		String arrayElements[] = {"Testing","Manual Testing", "Java","Automation Testing", 
                                                         "Software Testing","Java", "Testing"};
		System.out.println("********* Streams using frequency *********");
		List<String>list=Arrays.asList(arrayElements);
		Set<String>eleList=list.stream().filter(e -> Collections.frequency(list,e)>1)
				.collect(Collectors.toSet());
		System.out.println(eleList);
	}
}

Conclusion:

I hope all 6 different ways of finding duplicate elements in the array are clear. From now on, if you are attending any interview, please don’t explain only the brute force approach. Explaining these various methods in the interview will give you better opportunities.

So please practice and let me know if you have any issues or other findings about the duplicate elements; please feel free to put them in the comment section. definitely, I’ll have a look and try to clear the issues.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment