I have two Lists, say List1 and List2. I need to remove elements from List2 if that is already present in List1
To avoid ConCurrentModificationException, I have tried with ListIterator
employeeList1 // data present
employeeList2 // data present
ListIterator<Employee> zeroList=employeeList2.listIterator();
//remove employee if already present in list1
while(zeroList.hasNext()){
for(Employee employee : employeeList1){
if(zeroList.next().getID().equals(employee.getId())){
zeroList.remove();
}
}
}
I am getting the below exception inside the if condition
java.util.NoSuchElementException
It is possible that element might not be present in List1, but checking the condition is necessary.
You can use removeAll
method on collection from which you want to remove the elements and pass the collection as arguments which contains the elements you want to remove.
List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("p");
list2.add("q");
list2.removeAll(list1);
System.out.println(list2);
Removes a
from list2 as it was present in list1 and prints p
and q
only,
[p, q]
Edit: Here is a sample code for Employee
class while yours might be a different one but as you said your key is employeeId
hence equals
and hashCode
methods needs to play on employeeId
only.
static class Employee {
private long employeeId;
private String name;
// whatever more variables
public Employee(long employeeId, String name) {
this.employeeId = employeeId;
this.name = name;
}
public String toString() {
return String.format("Employee[employeeId=%s, name=%s]", employeeId, name);
}
@Override
public boolean equals(Object o) {
if (o instanceof Employee) {
return this.employeeId == ((Employee) o).employeeId;
}
return false;
}
@Override
public int hashCode() {
return new Long(employeeId).hashCode();
}
}
public static void main(String[] args) throws Exception {
List<Employee> list1 = new ArrayList<>();
list1.add(new Employee(1, "a"));
list1.add(new Employee(2, "b"));
list1.add(new Employee(3, "c"));
List<Employee> list2 = new ArrayList<>();
list2.add(new Employee(1, "a"));
list2.add(new Employee(4, "d"));
list2.add(new Employee(5, "e"));
list2.removeAll(list1);
System.out.println(list2);
}
Try using this code and see what it prints and then just comment both equals
and hashCode
method and then see what happens. After you comment those two methods, the object present in list1 will not be removed as list doesn't know when the two objects are equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With