java:S6204 false positive for modifying a list through Iterator.remove()

Product: SonarQube Community (self-hosted)
sonar-java version: sonar-java 8.28.0.43176 on SonarQube Community Build 26.4.0.121862
Java source level: 21 (javac 21, source/target 17)

Rule

java:S6204 — “Stream.toList()” should be used instead of “collect(Collectors.toList())”

Description

S6204 incorrectly suggests replacing collect(Collectors.toList()) with Stream.toList() when the resulting list is later modified through Iterator.remove(). The rule recognizes direct mutations like removeIf(...) but misses equivalent iterator-based mutations, causing a false positive.

Reproducer

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class Sample {

    // Not flagged by S6204 (correct — list is mutated).
    public List<String> processA(List<String> source) {
        List<String> result = source.stream()
                .map(String::trim)
                .collect(Collectors.toList());
        result.removeIf(String::isEmpty);
        return result;
    }

    // Flagged by S6204 (false positive — list is also mutated,
    // via Iterator.remove(), so Stream.toList() would throw UOE).
    public List<String> processB(List<String> source) {
        List<String> result = source.stream()
                .map(String::trim)
                .collect(Collectors.toList());
        Iterator<String> it = result.iterator();
        while (it.hasNext()) {
            if (it.next().isEmpty()) {
                it.remove();
            }
        }
        return result;
    }
}

Thanks for the example, we are already tracking this kind of issues with the rule, I’ll add this thread to this existing ticket