Video in progress

Strong Junior 🌊 Streams and lambdas

What happens if you modify the source list inside a stream?

Usually you get a ConcurrentModificationException, or the result is unpredictable. Streams have a "non-interference" rule: the source must not be touched while the chain is running. Use removeIf to delete, and filter + toList for a new list.

📖 Answer

List<String> list = new ArrayList<>(List.of("a", "b", "c"));

list.stream()
    .filter(s -> s.equals("b"))
    .forEach(list::remove);    // ConcurrentModificationException

ArrayList's spliterator checks modCount and throws an exception if it notices a change. Some collections might not throw, but the result is unreliable anyway.

The right ways:

// remove in place
list.removeIf(s -> s.equals("b"));

// get a new list
List<String> rest = list.stream().filter(s -> !s.equals("b")).toList();

// modify in place
list.replaceAll(String::toUpperCase);

The same rule applies to other side effects inside a lambda: mutating the elements themselves (u.setActive(false) inside map) technically works, but makes the code confusing. If you need to modify objects, a plain loop is clearer.