Find duplicate elements in an array

This is most common interview question in java now-a-days. There are many techniques to find duplicate elements in array in java like using Collections.frequency(). I am writing yet another solution which is much easier and fast.

Here an array of integers is having 10 integers and 1 and 8 are duplicate integers. You need to filter them out.

package com.howtodoinjava.interview;

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

public class DuplicateInArray 
	public static void main(String[] args) 
		int[] array = {1,1,2,3,4,5,6,7,8,8};
		Set<Integer> set = new HashSet<Integer>();
		for(int i = 0; i < array.length ; i++) 
			//If same integer is already present then add method will return FALSE 
			if(set.add(array[i]) == false) 
				System.out.println("Duplicate element found : " + array[i]);


Duplicate element found : 1
Duplicate element found : 8

In this solution, all you have to do is to iterate over array and all elements in a set one by one. If Set.add() method returns false then element is already present in set and thus it is duplicate.

Happy Learning !!

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial