Tuesday 18 August 2015

Java program to find duplicate element between two arrayList




You can find common element between two arrays by two ways i.e. either you can use for loop and compare both the array elements or you can convert array into list and can use retainAll() method.

1) Using For Loop:-

/**  
  * @author Dixit  
  *  
  */  
 public class DuplicateElements {  
      public static void main(String a[]){  
     int[] arr1 = {1,2,3,4,5};  
     int[] arr2 = {4,8,9,7,2};  
     for(int i=0;i<arr1.length;i++){  
       for(int j=0;j<arr2.length;j++){  
         if(arr1[i]==arr2[j]){  
           System.out.println(arr1[i]);  
         }  
       }  
     }  
   }  
 }  

2) Using retainAll() method of List:-

 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.Collections;  
 import java.util.HashSet;  
 import java.util.List;  
 import java.util.Set;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class DuplicateElements {  
      public static void main(String a[]) {  
           int[] arr1 = { 1, 2, 3, 4, 5 };  
           int[] arr2 = { 4, 8, 9, 7, 2 };  
           List<Integer> list1 = new ArrayList<Integer>();  
           for (int index = 0; index < arr1.length; index++) {  
                list1.add(arr1[index]);  
           }  
           List<Integer> list2 = new ArrayList<Integer>();  
           for (int index = 0; index < arr2.length; index++) {  
                list2.add(arr2[index]);  
           }  
           list1.retainAll(list2);  
           System.out.println("CommonElements : " + list1);  
      }  
 }  




Enjoy programming :)


No comments:

Post a Comment