Video in progress

What is wrong with the following code, and how do you fix it?

List<String> errors = new ArrayList<>();

long valid = requests.stream()
        .map(r -> {
            if (r.amount() <= 0) errors.add("Noto'g'ri summa: " + r.id());
            return r;
        })
        .filter(r -> r.amount() > 0)
        .count();

Writing to an outer list inside map is a side effect. On a sequential stream it looks like it works, but on a parallel one the ArrayList gets corrupted, and with a terminal operation like count() the map may not be called at all. The result should be gathered with a collector.

📖 Answer

There are two problems here.

The first: the lambda changes outside state. The stream documentation calls such lambdas "stateful" and asks you to avoid them. If someone adds .parallel() tomorrow, several threads will write to a single ArrayList: elements can be lost, or you can get an ArrayIndexOutOfBoundsException.

The second is subtler. In the current code there's a filter, so count() traverses the elements. But if the filter is removed, Java 9+ may compute count() from the source size and never call map at all, so errors stays empty.

The fixed version turns the validation into a result:

Map<Boolean, List<Request>> parts = requests.stream()
        .collect(Collectors.partitioningBy(r -> r.amount() > 0));

long valid = parts.get(true).size();
List<String> errors = parts.get(false).stream()
        .map(r -> "Noto'g'ri summa: " + r.id())
        .toList();

The rule: a lambda in map or filter should return a result based only on its input element. If you need to write to the outside, that's a job for forEach or a plain loop.