So I have this method that is supposed to find pairs inside a collection, for this purpose I use a nested loop. However I always get concurrent modification exception even though I'm using an iterator. I guess as both iterators iterate over the same collection, they are both trying to modify it at the same time and this is why I get this exception. Can you please help me avoid this error by accomplishing the same results.
private List<Pair<Document, Document>> createPairDocument(List<Document> documentsToIterate){
List<Pair<Document, Document>> pairDocList = new ArrayList<>();
//iterators are used to avoid concurrent modif exception
Iterator<Document> iterator0 = documents.iterator();
while(iterator0.hasNext()){
Document dl0 = iterator0.next();
Iterator<Document> iterator1 = documents.iterator(); //returns new instance of iterator
while(iterator1.hasNext()){
Document dl1 = iterator1.next();
if (dl1.relatedTo(dl0) && dl0.relatedTo(dl1)){
pairDocList.add(Pair.of(dl0, dl1));
//these docs should be removed to avoid creating the same relation again
iterator0.remove();
iterator1.remove();
break;
}
}
}
return pairDocList;
}