如何根据属性找到两个数组列表之间的差异? [英] How to find the differences between two Array Lists based on a property?

查看:28
本文介绍了如何根据属性找到两个数组列表之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two array list. Each has list of Objects of type Employee.

Employee 类如下所示

The Employee class looks like below

    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

}

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

I need to find the differences between the two lists based on a property of the employee object which is employee id.

员工 ID 是手动生成的唯一 ID,分配给每个员工.

Employee id is manually generated unique id given to each employee.

    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



    }

}

推荐答案

覆盖 Employeeequals()hashcode() 方法在检查相等性时仅使用 employeeId 的类(我不确定为什么需要 id 字段.您可能还需要合并它).NetBeans/Eclipse IDE 可以为您做到这一点.然后,您可以创建原始列表的副本,并使用 List.removeAll() 计算差异.

Override equals() and hashcode() methods of your Employee class to only use employeeId when checking for equality (im not sure about why you need the id field. you might what to incorporate it as well). NetBeans / Eclipse IDEs can do this for you. Then you can create a copy of your original lists and use List.removeAll() to calculate difference.

这篇关于如何根据属性找到两个数组列表之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆