Skip to content

Commit

Permalink
(Sonar) Fixed finding: "Stream.toList() should be used instead of `…
Browse files Browse the repository at this point in the history
…collectors`" (#430)

## Remediation

This change fixes "`Stream.toList()` should be used instead of
`collectors`" (id =
[java:S6204](https://rules.sonarsource.com/java/RSPEC-6204)) identified
by Sonar.

## Details

This change modernizes a stream's `List` creation to be driven from the
simple, and more readable
[`Stream#toList()`](https://docs.oracle.com/javase/16/docs/api/java.base/java/util/stream/Collectors.html#toList())
method.

Our changes look something like this:

```diff
- List<Integer> numbers = someStream.collect(Collectors.toList());
+ List<Integer> numbers = someStream.toList();
```

<details>
  <summary>More reading</summary>

*
[https://rules.sonarsource.com/java/RSPEC-6204/](https://rules.sonarsource.com/java/RSPEC-6204/)
</details>

🧚🤖  Powered by Pixeebot  

[Feedback](https://ask.pixee.ai/feedback) |
[Community](https://pixee-community.slack.com/signup#/domain-signup) |
[Docs](https://docs.pixee.ai/) | Codemod ID:
[sonar:java/replace-stream-collectors-to-list-s6204](https://docs.pixee.ai/codemods/java/sonar_java_replace-stream-collectors-to-list-s6204)
![](https://d1zaessa2hpsmj.cloudfront.net/pixel/v1/track?writeKey=2PI43jNm7atYvAuK7rJUz3Kcd6A&event=DRIP_PR%7Cpixee%2Fcodemodder-java%7C3fbd9552ce45b43b166a67aade0450c3c7a085c2)



<!--{"type":"DRIP","codemod":"sonar:java/replace-stream-collectors-to-list-s6204"}-->

---------

Co-authored-by: pixeebot[bot] <104101892+pixeebot[bot]@users.noreply.github.com>
Co-authored-by: Ryan Dens <[email protected]>
  • Loading branch information
pixeebot[bot] and ryandens authored Jul 25, 2024
1 parent a069684 commit f8af718
Show file tree
Hide file tree
Showing 10 changed files with 14 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
Expand Down Expand Up @@ -62,8 +61,7 @@ private List<CodemodChange> processWebXml(final CodemodInvocationContext context
Set<Integer> linesAffected = xmlChange.linesAffected();

// add the weaves to the context
List<CodemodChange> changes =
linesAffected.stream().map(CodemodChange::from).collect(Collectors.toList());
List<CodemodChange> changes = linesAffected.stream().map(CodemodChange::from).toList();

// overwrite the previous web.xml with the new one
Files.copy(xmlChange.transformedXml(), file, StandardCopyOption.REPLACE_EXISTING);
Expand Down Expand Up @@ -107,8 +105,6 @@ public String getIndividualChangeDescription(final Path filePath, final CodemodC

@Override
public List<CodeTFReference> getReferences() {
return reporter.getReferences().stream()
.map(u -> new CodeTFReference(u, u))
.collect(Collectors.toList());
return reporter.getReferences().stream().map(u -> new CodeTFReference(u, u)).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -485,9 +485,7 @@ public Integer call() throws IOException {
reportGenerator.createReport(
projectDirectory.toPath(),
String.join(" ", args),
sarifs == null
? List.of()
: sarifs.stream().map(Path::of).collect(Collectors.toList()),
sarifs == null ? List.of() : sarifs.stream().map(Path::of).toList(),
results,
elapsed);
ObjectMapper mapper = new ObjectMapper();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -116,9 +115,7 @@ private static CodemodReporterStrategy getCodemodReporterStrategy(
String change = parent.get("change").asText();
ArrayNode referencesNode = (ArrayNode) parent.get("references");
List<String> references =
StreamSupport.stream(referencesNode.spliterator(), false)
.map(JsonNode::asText)
.collect(Collectors.toList());
StreamSupport.stream(referencesNode.spliterator(), false).map(JsonNode::asText).toList();

return new CodemodReporterStrategy() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ private FilesUpdateResult updateFiles(
List<Path> filesFailedToChange = List.of();

// update the dependencies in the manifest file if needed
// We suppress warnings because we conditionally remove items from this list instance
@SuppressWarnings("java:S6204")
List<DependencyGAV> dependencies =
codemodChanges.stream()
.map(CodemodChange::getDependenciesNeeded)
Expand All @@ -267,7 +269,7 @@ private FilesUpdateResult updateFiles(
.map(
change ->
translateCodemodChangetoCodeTFChange(codeChanger, filePath, change, pkgActions))
.collect(Collectors.toList());
.toList();

// make sure we add the file's entry first, then the dependency entries, so the causality
// is clear
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public Optional<XPathStreamProcessChange> process(
DocumentHelper.selectNodes(xpathExpression, doc).stream()
.map(node -> (LocationAwareElement) node)
.map(element -> new Position(element.getLine(), element.getColumn()))
.collect(Collectors.toUnmodifiableList());
.toList();

if (httpMethodPositions.isEmpty()) {
return Optional.empty();
Expand Down Expand Up @@ -97,7 +97,7 @@ public Optional<XPathStreamProcessChange> process(
// remove the empty leftover lines affected by our changes if there are any
Set<Integer> linesAffected =
httpMethodPositions.stream().map(pos -> pos.line()).collect(Collectors.toUnmodifiableSet());
List<String> lines = transformedXml.lines().collect(Collectors.toUnmodifiableList());
List<String> lines = transformedXml.lines().toList();
List<String> updatedLines = new ArrayList<>(lines.size() - linesAffected.size());
for (int i = 1; i <= lines.size(); i++) {
String actualLine = lines.get(i - 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
* Responsible for binding {@link Parameter}s to codemods. Also performs validation to ensure
Expand All @@ -33,7 +32,7 @@ protected void configure() {
this.injectableParameters.stream()
.filter(param -> param.isAnnotationPresent(CodemodParameter.class))
.filter(param -> param.getType().equals(Parameter.class))
.collect(Collectors.toUnmodifiableList());
.toList();

for (java.lang.reflect.Parameter param : codemodParameters) {
CodemodParameter codemodParameter = param.getAnnotation(CodemodParameter.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

/** Gives access to raw files for performing arbitrary changes. */
public abstract class RawFileChanger implements CodeChanger {
Expand Down Expand Up @@ -45,8 +44,6 @@ public String getIndividualChangeDescription(final Path filePath, final CodemodC

@Override
public List<CodeTFReference> getReferences() {
return reporter.getReferences().stream()
.map(u -> new CodeTFReference(u, u))
.collect(Collectors.toList());
return reporter.getReferences().stream().map(u -> new CodeTFReference(u, u)).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import io.codemodder.codetf.CodeTFReference;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

/** Uses JavaParser to change Java source files. */
public abstract class JavaParserChanger implements CodeChanger {
Expand Down Expand Up @@ -41,8 +40,6 @@ public String getIndividualChangeDescription(final Path filePath, final CodemodC

@Override
public List<CodeTFReference> getReferences() {
return reporter.getReferences().stream()
.map(u -> new CodeTFReference(u, u))
.collect(Collectors.toList());
return reporter.getReferences().stream().map(u -> new CodeTFReference(u, u)).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import javax.xml.stream.XMLStreamException;
import org.dom4j.DocumentException;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -183,7 +182,7 @@ static Optional<VersionQueryResponse> queryVersions(ProjectModel projectModel)
if (queryVersionResult.size() == 1) {
List<VersionDefinition> queryVersionResultList =
queryVersionResult != null && !queryVersionResult.isEmpty()
? queryVersionResult.stream().collect(Collectors.toList())
? queryVersionResult.stream().toList()
: Collections.emptyList();
Version mappedVersion = mapVersion(queryVersionResultList.get(0).getValue());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.net.URL;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import org.dom4j.DocumentException;

/**
Expand Down Expand Up @@ -47,8 +46,7 @@ public ProjectModelFactory withPomFile(POMDocument pomFile) {
*/
public ProjectModelFactory withParentPomFiles(Collection<POMDocument> parentPomFiles) {
this.parentPomFiles =
new ArrayList<>(
parentPomFiles.stream().filter(Objects::nonNull).collect(Collectors.toList()));
new ArrayList<>(parentPomFiles.stream().filter(Objects::nonNull).toList());
return this;
}

Expand Down

0 comments on commit f8af718

Please sign in to comment.