Finding the different elements between two ArrayLists in Java

后端 未结 6 1274
滥情空心
滥情空心 2021-02-06 05:43

How can I know the different element between 2 array list in java? I need the exact element not a Boolean value which can be retrieved using removeAll().

6条回答
  •  深忆病人
    2021-02-06 06:16

    Call the method ReturnArrayListDiffElements passing two array lists. An array list which is the difference between two passed array lists will be returned

    public ArrayList ReturnArrayListDiffElements(ArrayList arrList1, ArrayList arrList2){   
        ArrayList List1 = new ArrayList();  
        ArrayList List2 = new ArrayList();  
        ArrayList List3 = new ArrayList();  
        ArrayList List4 = new ArrayList();
    
        List1.addAll(arrList1);     
        List2.addAll(arrList2);
    
        List3 = ReturnArrayListCommonElements(List1,List2);
    
        List1.removeAll(List3);     
        List2.removeAll(List3);     
        if(List1.size() > 0){
            List4.add("Distinct elements in Array List 1");     
            List4.addAll(List1);    
        }   
        if(List2.size() > 0){       
            List4.add("Distinct elements in Array List 2");
            List4.addAll(List2);    
        }   
    
        return List4; 
    }
    
    public ArrayList ReturnArrayListCommonElements(ArrayList arrList1, ArrayList arrList2){     
        ArrayList List1 = new ArrayList();  
        ArrayList List2 = new ArrayList();  
        ArrayList List1A = new ArrayList();     
        ArrayList List2A = new ArrayList();     
        ArrayList List1B = new ArrayList();     
        ArrayList List3 = new ArrayList();
    
        List1.addAll(arrList1);     
        List2.addAll(arrList2);        
        List1A.addAll(arrList1);    
        List2A.addAll(arrList2);    
        List1B.addAll(arrList1);
    
        int intList1Size, intList2Size;     
        List1.removeAll(List2);
        intList1Size = List1.size();
    
        List2.removeAll(List1A);    
        intList2Size = List2.size();
    
        if (intList1Size == 0 && intList2Size ==0) {          
            List3.addAll(List1B);       
            return List3; 
        } else {
            List3.addAll(List1B);       
            List1B.removeAll(List2A);       
            List3.removeAll(List1B);        
            return List3;   
        }
    }
    

提交回复
热议问题