CodexBloom - Programming Q&A Platform

How to implement guide with concurrentmodificationexception when using arraylist in java 14 with streams

๐Ÿ‘€ Views: 4775 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-28
java java-14 streams concurrency Java

I've been banging my head against this for hours... I'm converting an old project and I'm working with a `ConcurrentModificationException` while trying to modify an `ArrayList` within a stream operation in Java 14. I have a list of items that I want to filter and simultaneously remove certain elements based on a condition, but I keep running into this exception. Hereโ€™s a simplified version of my code: ```java import java.util.ArrayList; import java.util.List; public class StreamExample { public static void main(String[] args) { List<String> items = new ArrayList<>(); items.add("apple"); items.add("banana"); items.add("cherry"); items.add("date"); // This will throw ConcurrentModificationException items.stream().filter(item -> { if (item.startsWith("b")) { items.remove(item); } return true; }).forEach(System.out::println); } } ``` I tried using `Iterator` to remove items instead, but that seems to defeat the purpose of using streams for this operation. I was also considering using `List.removeIf()` before the stream operation, but I want to keep it as a single pipeline where possible. Can someone guide to understand the best way to handle this situation without running into concurrency issues? I'm also curious if thereโ€™s a way to do this more idiomatically in Java 14. Any suggestions would be greatly appreciated! What would be the recommended way to handle this? Thanks for any help you can provide!