I have 2 lists and want to copy some element from one to another, i.e. there are old and new employees list I need to union 2 lists and delete the elements that include to the old list but not include in the new one.
I could solve the part of getting the union and intersection by using TreeSet and override the equals and hashcode functions of the Employees class....
Now, I want to exclude the elements that are in the old but not in the new and add them to the "deletedList"....which I got "ConcurrentModificationException"
I tried this instead of "iterator" but the same result: for(Employees e : employeesListDB)
Also I tried "CopyOnWriteArrayList" instead of "ArrayList" but no change!!
but the problem now that at the initialization of the empty list "deletedList" it is filled with multiple null elements before the add function!
Here is the code:
List<Employees> employeesListDB = this.findAll();
Set<Employees> empSet = new TreeSet<Employees>(new EmployeeComparator());
empSet.addAll(employeesList);
List<Employees> deletedList = new ArrayList<Employees>();
Employees e = new Employees();
ListIterator<Employees> itr = employeesListDB.listIterator();
for(itr.hasNext()) {
e = (Employees)itr.next();
if(!empSet.contains(e)) {
deletedList.add(e);
}
}
A counter Example:
The oldlist "employeesListDB" the employees list from the database:
[
{
"email":"[email protected]"
},
{
"email":"[email protected]"
},
{
"email":"[email protected]"
},
{
"email":"[email protected]"
},
{
"email":"[email protected]"
},
{
"email":"[email protected]"
}
]
The new list to be added:
[
{
"email":"[email protected]"
},
{
"email":"[email protected]"
},
{
"email":"[email protected]"
}
]
The deleted list that I want:
[
{
"email":"[email protected]" }, {
"email":"[email protected]" }, {
"email":"[email protected]" }, {
"email":"[email protected]" }, {
"email":"[email protected]" } ]
Sara mail will be updated...
Employee class has two fields {id,email} the new list (the list to be added to the db) is a list of only emails, id field are not recognized yet but the old list has the complete bean fields ...to compare between these 2 list I should override the Comparator to ignore the id field; Finding duplicates in a List ignoring a field
JUST I need to know, why when I use set.add operation, it adds the unique emails only! the original size of the list was 36 elements after adding it into a set it becomes only 16!!
Set<Employees> oldSet = new TreeSet<Employees>(new EmployeeComparator());
oldSet.addAll(employeesListDB);
Set<Employees> newSet = new TreeSet<Employees>(new EmployeeComparator());
newSet.addAll(employeesList);
Set<Employees> deleted = Sets.difference(oldSet, newSet);
Try it this way (Made a small TestCase):
}
simple Employee class:
output: