比较两个arraylist内容并将不匹配的内容存储在另一个arraylist中

Jav*_*ava 5 java compare arraylist

我想比较两个arraylist内容.

我以这种方式存储对象.

对于Arraylist 1:

Employee e1=new Employee();

e1.setID("1");
e1.setID("2");

ArrayList<Employee>list1 = new ArrayList<Employee>(); 

if(e1!=null){
    list1.add(e1);
}
Run Code Online (Sandbox Code Playgroud)

对于Arraylist 2:

Employee e2=new Employee();

e2.setID("1");
e2.setID("2");
e2.setID("4");

ArrayList<Employee>list2 = new ArrayList<Employee>(); 

if(e2!=null){
    list2.add(e2);
}
Run Code Online (Sandbox Code Playgroud)

现在我试图以这种方式比较上面的arraylist内容

ArrayList<Employee>unmatchedList = new ArrayList<Employee>();   

for (Employee l1 : list1){                               
    if(!list2.contains(l1.getID())){    
        System.out.println("list2 does not contains this ID"+l1.getID());   
        Employee e3=new Employee();          
        e3.setID(l1.getID());

        if(unmatchedList==null){            
        unmatchedList=new ArrayList<Employee>();            
        unmatchedList.add(e3);          
        }

        if(unmatchedList!=null){                            
            unmatchedList.add(e3);              
        }                       
    }
}
Run Code Online (Sandbox Code Playgroud)

但我并没有将正确的unmatchedList内容仅作为"4".我得到unmatchedList为"1"和"2"这是错误的.那么如何才能在"unmatchedList"中获得不匹配的内容

Dim*_*tri 5

如果您的类Employee定义如下:

public class Employee {

private int id;

public Employee(int id){
    this.id = id;
}

public int getId() {
    return id;
}

@Override
public String toString() {
    return "Id : " + this.id;
}

@Override
public boolean equals(Object obj) {
    return (obj instanceof Employee) && this.id == ((Employee)obj).getId();
}
Run Code Online (Sandbox Code Playgroud)

在Main方法中,您可以检索不匹配的内容,如下所示:

 public static void main( String[] args )
{
   List<Employee> l1 = new ArrayList<Employee>();
   l1.add(new Employee(1));
   l1.add(new Employee(2));
   l1.add(new Employee(3));
   l1.add(new Employee(4));
   l1.add(new Employee(5));


   List<Employee> l2 = new ArrayList<Employee>();
   l2.add(new Employee(4));
   l2.add(new Employee(5));


   l1.removeAll(l2);
   System.out.println(l1);

}
Run Code Online (Sandbox Code Playgroud)

这将打印: [Id : 1, Id : 2, Id : 3]

请注意,对于此工作,您必须覆盖该equals方法.