如何根据属性查找两个数组列表之间的差异?

ash*_*ram 5 java arraylist find

我有两个数组列表.每个都有Employee类型的对象列表.

Employee类如下所示

    public class Employee {

    Employee(String firstname, String lastname, String employeeId) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.employeeId = employeeId;
    }

    private int id; // this is the primary key from employee table

    private String firstname;

    private String lastname;

    private String employeeId; // manually assigned unique id to each employee

    // getters and setters

}
Run Code Online (Sandbox Code Playgroud)

我需要根据员工对象的属性(员工ID)找到两个列表之间的差异.

员工ID是为每个员工手动生成的唯一ID.

    import java.util.ArrayList;
import java.util.List;


public class FindDifferences {

    public static void main(String args[]){
        List<Employee> list1 = new ArrayList<Employee>(); 
        List<Employee> list2 = new ArrayList<Employee>(); 

        list1.add(new Employee("F1", "L1", "EMP01"));
        list1.add(new Employee("F2", "L2", "EMP02"));
        list1.add(new Employee("F3", "L3", "EMP03"));
        list1.add(new Employee("F4", "L4", "EMP04"));
        list1.add(new Employee("F5", "L5", "EMP05"));

        list2.add(new Employee("F1", "L1", "EMP01"));
        list2.add(new Employee("F2", "L2", "EMP02"));
        list2.add(new Employee("F6", "L6", "EMP06"));
        list2.add(new Employee("F7", "L7", "EMP07"));
        list2.add(new Employee("F8", "L8", "EMP08"));

        List<Employee> notPresentInList1 = new ArrayList<Employee>(); 
        // this list should contain EMP06, EMP07 and EMP08

        List<Employee> notPresentInList2= new ArrayList<Employee>(); 
        // this list should contain EMP03, EMP04 and EMP05



    }

}
Run Code Online (Sandbox Code Playgroud)

小智 7

覆盖equals()和类的hashcode()方法EmployeeemployeeId在检查相等性时使用(我不确定你为什么需要该id字段.你也可以将它包含在内).NetBeans/Eclipse IDE可以为您完成此任务.然后,您可以创建原始列表的副本,并用于List.removeAll()计算差异.