Home » Java » java – Get Duplicates from an array and Copy that Duplicates in another Array-Exceptionshub

java – Get Duplicates from an array and Copy that Duplicates in another Array-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:
public class storeDuplicateArrayInAnotherArray
    {

     public static void main(String[] args) 
     {

            int[] a = {1,2,2,3,3,4,4,5,6,6,7};

            Set<Integer> arr = new HashSet<Integer>();
            System.out.println("Duplicate Array::");
            for(Integer x:a) {
                if(arr.add(x) == false) {
                    System.out.println(x);
                }
            }
     }
}
How to&Answers:

Use add method in Set

int[] a = { 1, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7 };
Set<Integer> set = new HashSet<>();
for (int k : a) {
    if (!set.add(k)) {
        System.out.println("Duplicate: " + k);
    }
}

Answer:

you can do it in simply checking elment present in same array or not and store it in different collection

int[] arr = {1,2,2,3,3,4,4,5,6,6,7};
ArrayList<Integer> list = new ArrayList<>(   
for(int i = 0; i < arr.length; i++) {  
     for(int j = i + 1; j < arr.length; j++) {  
          if(arr[i] == arr[j])  
            list.add(arr[j]);  
     }  
 } 
 System.out.println("Duplicates element is: "+ list);