Senior
```java import java.util.ArrayList; import java.util.List; public class StreamTest { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Ivan"); names.add("Max"); names.add("Alex"); names.stream().forEach(name -> { System.out.println(name); names.add(name + " the Great"); }); System.out.println(names); } } ```
sobes.tech AI
Answer from AI
In this code, the list names is modified during iteration through it using the Stream API.
Java Stream does not support modifying the collection while processing it — this will lead to a ConcurrentModificationException.
In your example:
names.stream().forEach(name -> {
System.out.println(name);
names.add(name + " the Great");
});
Attempting to add elements to names during traversal will throw an exception.
If you run this code, you will get:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at ...
To avoid the error, do not modify the collection during iteration. For example, collect new elements in a separate list, then add them:
List<String> additions = new ArrayList<>();
names.stream().forEach(name -> {
System.out.println(name);
additions.add(name + " the Great");
});
names.addAll(additions);
System.out.println(names);
This way, you safely extend the list after the iteration.