java - Merging Arraylist of Objects and removing duplicates based on a field value -
i looking best solution below requirements.
i have class similar classa
below
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 , setters above fields } }
and have 2 objects (obj1, ojb2)
of classa
. requirement merge 2 objects , remove duplicates.
example:
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]]
after merging result should like:
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>]}
implement equals
, hashcode
plana
:
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 }); } }
then use set
:
set<classa.plana> merged = new hashset<classa.plana>(); merged.addall(obj1.getpriceplan()); merged.addall(obj2.getpriceplan());
a set
automatically removes duplicates.