2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

find duplicates and list the duplicates in array

I have an Array of 10,000 unsorted elements with duplicates .

For example : Array a = [1,2,3,4,5,5,6,7,8,9,1,2,3.......upto 10,000 elements]  .

  How can i  find duplicates and list the duplicates?

userimage

Find the below snippet with complete example with minimal set of data,


package com.test.code;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FindDuplicateInArray {
    public List<Integer> duplicates(final int... data) {
        List<Integer> duplicateList = new ArrayList<Integer>();
        Set<Integer> set = new HashSet<Integer>();
        for (int i : data) {
            if (set.contains(i)) {
                duplicateList.add(i);
            } else{
                set.add(i);
            }
        }
        return duplicateList;
    }

    public static void main(String[] args) {
        int[] intArray = { 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 1, 2, 3 };
        System.out.println(new FindDuplicateInArray().duplicates(intArray));
    }
}


Result : [5, 1, 2, 3]

Answer is