java - 比较两个arraylist的内容,将不匹配的内容存入另一个arraylist

标签 java arraylist compare

我想比较两个数组列表的内容。

我正在以这种方式在其中存储对象。

对于数组列表 1:

Employee e1=new Employee();

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

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

if(e1!=null){
    list1.add(e1);
}

对于数组列表 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);
}

现在我正在尝试以这种方式比较上面的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);              
        }                       
    }
}

但我没有得到正确的 unmatchedList 内容作为 "4"only 。 我得到的 unmatchedList 为“1”和“2”,这是错误的。 那么如何才能只在“unmatchedList”中获取不匹配的内容

最佳答案

如果您的类 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();
}

在 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);

}

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

请注意,对于这项工作,您必须覆盖 equals 方法。

关于java - 比较两个arraylist的内容,将不匹配的内容存入另一个arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509573/

相关文章:

java - 是否可以动态混合ListView和TextView?

java - java.util.List 的 contains 方法线程安全吗?

r - 两个数字向量上的全对全 setdiff 具有用于接受匹配的数字阈值

python:比较不同日期类型的数据

java - 如何解决 "This element has no attached source and the Javadoc could not be found in the attached Javadoc"?

java - 如何从java中的线程传播异常?

java - 将列表添加到二维数组列表

c - C 中的 If 语句输出无效

java - 使用 JComboBox 作为 JTable 中的单元格编辑器的焦点问题

java - 为什么我的数组被覆盖了java