CodexBloom - Programming Q&A Platform

Java 17 Modifying LinkedList Inside forEach Causes ConcurrentModificationException

πŸ‘€ Views: 84 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
java collections concurrent-modification-exception Java

I'm maintaining legacy code that I'm working with a `ConcurrentModificationException` when trying to modify a `LinkedList` inside a `forEach` loop. I'm using Java 17, and here’s the code snippet I'm working with: ```java import java.util.LinkedList; import java.util.List; public class Example { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("A"); list.add("B"); list.add("C"); list.forEach(item -> { if (item.equals("B")) { list.remove(item); // This line throws ConcurrentModificationException } }); } } ``` I expected the list to remove the item without any issues, but instead, I get: ``` Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:100) at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:123) at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:101) ... ``` I've tried using an `Iterator` to remove items safely, but I want to understand if there's a more idiomatic approach in Java 17. Can someone suggest a solution or best practice for modifying a collection while iterating over it? Or is there a better way to handle this scenario with streams or other collection types? My development environment is Debian. Any examples would be super helpful. I've been using Java for about a year now. What am I doing wrong?