Write a java program to find duplicate elements in array?

This tutorial explains step by step how to print duplicate elements in an array.Let’s see the steps given below:

Steps to print duplicate elements in array

1)  create and initialize input array.

2)  create an empty set and name it as non duplicate set.

3)  create an empty set and name it as duplicates set.

4)  Iterate through the each element in array and check whether nonduplicates contains the element.If it is present add it to the duplicates set.

5)  If it is not present add it to non duplicates set.

6)  Finally Print the elements in duplicates set.

Java example to print duplicate elements in array

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

public class PrintDuplicateElementsArray {

	public static void main(String[] args) {
		String duplicates[]=new String[]{"java","spring","hibernate","java"};
		Set nonDuplicatesSet=new HashSet<>();
		Set duplicatesSet=new HashSet<>();
		for (String string : duplicates) {


 Output :


Leave a Reply

Your email address will not be published. Required fields are marked *