合并对象的Arraylist并根据字段值删除重复项

时间:2013-04-25 16:21:01

标签: java

我正在寻找满足以下要求的最佳解决方案。

我的课程类似于ClassA

public class ClassA {
    protected List<ClassA.PlanA> planA;

    public List<ClassA.PlanA> getPricePlan() {
        if (planA == null)
            planA = new ArrayList<ClassA.PlanA>();
        return this.planA;
    }

    public static class PlanA {
        protected String code;
        protected XMLGregorianCalendar startDate;
        protected XMLGregorianCalendar endDate;

        // Getters and setters for the above fields
    }   
}

我有两个(obj1, ojb2) ClassA的对象。要求是合并两个对象并删除重复项。

示例:

ClassA obj1=[PlanA =[code=AAA, startDate=2010/12/10, endDate=2011/12/10], PlanA =[code=BBB, startDate=2010/12/10 endDate=<null>]] 

ClassA obj2=[PlanA=[code=AAA, startDate=2011/12/10], PlanA= [code=CC, startDate=2011/12/10 endDate=<null>], PlanA= [code=BBB, startDate=2010/12/10 endDate=2011/12/10]]

合并后的结果应如下所示:

ClassA obj3=[PlanA[code=AAA, startDate=2011/12/10], PlanA= [code=CC, startDate=2011/12/10 endDate=<null>],PlanA= [code=BBB, startDate=2010/12/10 endDate=<null>]}

1 个答案:

答案 0 :(得分:2)

equals实施hashcodePlanA

public static class PlanA {

    protected String code;
    protected XMLGregorianCalendar startDate;
    protected XMLGregorianCalendar endDate;

    @Override
    public boolean equals(Object obj) {
        return obj instanceof PlanA && obj.hashCode() == hashCode();
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(new Object[] { code, startDate, endDate });
    }

}

然后使用Set

Set<ClassA.PlanA> merged = new HashSet<ClassA.PlanA>();
merged.addAll(obj1.getPricePlan());
merged.addAll(obj2.getPricePlan());

Set会自动删除重复项。