The warning “Replace this usage of ‘Stream.collect(Collectors.toUnmodifiableList())’ with 'Stream.toList()” is incorrect.
-
What language is this for?
Java 16 -
Which rule?
Replace this usage of ‘Stream.collect(Collectors.toUnmodifiableList())’ with ‘Stream.toList()’ -
Why do you believe it’s a false-positive/false-negative?
WhiletoList()
does return an unmodifiable list, it permits null values within the list. To ensure a list without any null values, one must usecollect(toUnmodifiableList())
as an alternative. However, when using this method, Sonar flags it as incorrectly, potentially overlooking errors that could be identified during list initialization. -
Used product:
SonarLint - IntelliJ Version 10.11.1.79663 in connected mode with SonarQube -
How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
// Example using Stream.collect(Collectors.toList())
List<String> listWithNulls = Stream.of("A", "B", null, "C")
.collect(Collectors.toList());
System.out.println("List with nulls (toList): " + listWithNulls);
// Example using Stream.collect(Collectors.toUnmodifiableList())
try {
List<String> unmodifiableList = Stream.of("A", "B", null, "C")
.collect(Collectors.toUnmodifiableList());
System.out.println("Unmodifiable list (toUnmodifiableList): " + unmodifiableList);
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: Collectors.toUnmodifiableList() does not allow nulls");
}
// Example using Stream.toList()
List<String> unmodifiableListWithNulls = Stream.of("A", "B", null, "C")
.toList();
System.out.println("Unmodifiable list with nulls (toList): " + unmodifiableListWithNulls);