I'm a beginner in Java and I have a problem with one task.
I'm trying to add an element to ArrayList but there is an exception: Exception in thread "main" java.util.ConcurrentModificationException
public Anagrams (String path) throws FileNotFoundException {
List<String> tmpList = new ArrayList<>();
Scanner scan = new Scanner(new File(path));
while(scan.hasNext()) {
tmpList.add(scan.next());
}
scan.close();
tmpList.forEach(word -> {
if(anList.isEmpty()) {
ArrayList<String> tmp1 = new ArrayList<String>();
tmp1.add(word);
anList.add(tmp1);
}
else {
anList.forEach(list -> {
if (isAnagram(word, list.get(0))) {
list.add(word);
} else {
ArrayList<String> tmp2 = new ArrayList<String>();
tmp2.add(word);
anList.add(tmp2);
}
});
}
});
}
I'm collecting words from a txt file and separate them into different Arrays if they are anagrams or not. I know I can't modify a collection while I'm iterating over it - but I can't figure it out how to avoid this exception.. Please, can you help me?