I have an iterator inside a thread and I am trying to remove the duplicate records.
Runnable readingThread = new Runnable() {
@Override
public void run() {
Iterator<Demand> iterator = null;
for (iterator = demandListFromFile.iterator(); iterator.hasNext();) {
Demand demand = iterator.next();
/**
* Find and assign the Item ID
*/
if (itemListHashMap.containsValue(demand.getItem().getItemName())) {
demand.getItem().setIditem(itemListHashMapReversed.get(demand.getItem().getItemName()));
} else {
unavailableItemsList.add(demand.getItem().getItemName());
}
/**
* Find and remove duplicate records
*/
for (Map.Entry<Date, String> entry : demandListHashMap.entries()) {
if (demand.getDueDate().equals(entry.getKey()) && demand.getItem().getItemName().equals(entry.getValue())) {
iterator.remove();
}
}
}
}
After removing few items, the iterator.remove throws the below exception
Exception in thread "Thread-0" java.lang.IllegalStateException
at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:1009)
at com.xxx.xxx.ui.Home$7.run(Home.java:455)
at java.base/java.lang.Thread.run(Thread.java:834)
Why is this happening? Please note I have removed the code after and before the iterator, to keep this post short.
iterator.remove();) ? or from the collection ? For more help please post minimal reproducible example and mark the line that throws the exception..remove()is being called within a nested loop, could you be calling it more than once? If so, this will result in the exception's being thrown. You should break out of the loop immediately after calling remove. And yeah, @c0der is right -- you need to create and post a minimal reproducible example to adequately allow the queastion to be answered without guessing.