fix: Replace Stream.collect(Collectors.toList()) with Stream.toList()#2288
fix: Replace Stream.collect(Collectors.toList()) with Stream.toList()#2288sonarqube-agent[bot] wants to merge 1 commit into
Conversation
Fixed issues: - AZ5AH3Zx14LASZpDSnJH for java:S6204 rule Generated by SonarQube Agent (task: 58d238e1-36d5-4c15-8eb5-4561ce93720a)
SummaryModernizes a single stream collection to use What reviewers should knowWhat to check:
Non-obvious decisions:
|
There was a problem hiding this comment.
LGTM! ✅
Clean, safe change. The project targets Java 17 (jdk.source.version=17), so Stream.toList() (Java 16+) is fully compatible. All callers of issues() only read the returned list (.get(0), hasSize(), assertThat()), so the switch to an unmodifiable list introduces no risk of UnsupportedOperationException. The Collectors import removal is correct — no other references to Collectors remain in the file.
There are ~35 other collect(Collectors.toList()) occurrences across python-frontend and python-checks production code that this PR does not touch, but that is out of scope for a targeted SonarQube remediation fix.
Updated TestRulesTest.java to use the modern Stream.toList() method instead of collect(Collectors.toList()), which is more efficient and returns an unmodified list. This resolves a SonarQube MAJOR issue and removes the now-unused Collectors import.
View Project in SonarCloud
Fixed Issues
java:S6204 - Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified. • MAJOR • View issue
Location:
its/plugin/it-python-plugin-test/src/test/java/com/sonar/python/it/plugin/TestRulesTest.java:163Why is this an issue?
In Java 8
Streamswere introduced to support chaining of operations over collections in a functional style. The most common way to save a result of such chains is to save them to some collection (usuallyList). To do so there is a terminal methodcollectthat can be used with a library ofCollectors. The key problem is that.collect(Collectors.toList())actually returns a mutable kind ofListwhile in the majority of cases unmodifiable lists are preferred. In Java 10 a new collector appeared to return an unmodifiable list:toUnmodifiableList(). This does the trick but results in verbose code. Since Java 16 there is now a better variant to produce an unmodifiable list directly from a stream:Stream.toList().What changed
Removes the now-unused import of
java.util.stream.Collectors, which is no longer needed after replacing.collect(Collectors.toList())with.toList(). This is a cleanup change that supports the main fix.SonarQube Remediation Agent uses AI. Check for mistakes.