There is a need for filtering in the business and foreach is trampled on. That’s how it was written.
user.forEach(u -> {
ageList.forEach(a -> {
if(u.getId().equals(a)) { user.remove(u); }}); }); }Copy the code
This is what it looks like.
Iterator<SocNearbyRespDto> ui = user.iterator();
while (ui.hasNext()){
SocNearbyRespDto u = ui.next();
ageList.forEach(a->{
if(! u.getId().equals(a)){ ui.remove(); }}); }}Copy the code
There are usually three kinds of loops in Java.
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + ",");
}
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + ",");
}
for (Integer i : list) {
System.out.print(i + ",");
}
Copy the code
List. foreach, like the third enhanced for loop in this code, decompiles
Integer i;
for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(i)){
i = (Integer)iterator.next();
}
Copy the code
Such calls in a for loop will appear abnormal ConcurrentModificationException.
Iterator works on a separate thread and has a mutex lock. After the Iterator is created, it creates a single indexed table that points to the original object. When the number of original objects changes, the contents of the index table do not change synchronously. Therefore, when the index pointer moves backwards, the object to be iterated cannot be found. So the Iterator thrown immediately in accordance with the principle of fail – fast Java. Util. ConcurrentModificationException anomalies.
So iterator.remove () is fine.