False Positive for squid:2175 in a stream with lambda

java

(Jason Horton) #1

Hello,

I have found a false positive with a collection being called with a different type, when it is actually the correct type, but only when the method is being called within a stream.

Versions used:
SonarQube: 7.2 (build 13530)
maven scanner: 3.4.1.1168

Error observed:
SonarQube says ‘A “Set” cannot contain a “E”’ when calling ‘contains’ or ‘remove’ (but not add?) in a stream using a lambda, but with identical code in a traditional for-loop, there is no issue raised. When using a method reference in the stream, the issue is not raised.

Code example:

public void test() {
    Set<Integer> used = new HashSet<>();
    List<List<Integer>> allInts = Collections.emptyList();
    List<Integer> list = new ArrayList<>();

    for (List<Integer> ints : allInts) {
        for (Integer i : ints) {
            if (!used.contains(i)) {
                list.add(i);
            }
        }
    }

    allInts.stream()
            .flatMap(List::stream)
            .filter(i -> !used.contains(i))
            .forEach(list::add);
}

Here is a screenshot of the issue:
sonar_bug2

Thanks!


(Andrei Epure) #3

Thank you for the detailed reproducer, I confirm it’s a false positive and opened SONARJAVA-2881 to track the issue.

Andrei