3

I have a few simple Java Streams in my code for these Streams SonarQube/Sonarlint shows as Noncompliant with the message:

Refactor the code so this stream pipeline is used.

Following are my Java Methods/Streams:

private static List<String> format(List<String> input) {
    return input.stream().map(i -> DomainName + "/path/file-" + i).toList();
}

Another Noncompliant code sample is:

private static List<String> format1(List<String> input) {
    return input.stream().map(String::toLowerCase).toList();
}

I believe these are simple Java Streams and they are working as expected for my requirement so not sure what's wrong with this. Can someone please explain what's wrong with this and how to fix the SonarQube issue?

Following is the Bug which is thrown by SonarQube: enter image description here

Another Clarification

Which of the below is good to use as per Sonar and coding perspective?

I am currently creating a List something like this:

final List<String> myList = new ArrayList<>();

Update

So SonarCube tells me to declare it as var so is it good to change it to

  1. var myList = new ArrayList<>(); or
  2. final var myList = new ArrayList<>();
BATMAN_2008
  • 2,788
  • 3
  • 31
  • 98
  • Probably it's because `toList` returns an unmodifiable list, whereas `collect(Collectors.toList())` returns a modifiable `ArrayList` instead, but I'm only guessing. See [here](https://stackoverflow.com/questions/65969919/differences-of-java-16s-stream-tolist-and-stream-collectcollectors-tolist) for reference – QBrute Mar 14 '22 at 14:48
  • Huh that's weird. Is it not aware of what's new in Java 16? What if you change `toList()` to `collect(Collectors.toList())`? Does that work? – Sweeper Mar 14 '22 at 14:48
  • @Sweeper I thought so hence I tried to change it to `input.stream().map(String::toLowerCase).collect(Collectors.toList())` but If I do that then I get another issue `"Stream.toList()" method should be used instead of "collectors" when unmodifiable list needed` and it informs me to use `toList`. It will give me one or another issue. – BATMAN_2008 Mar 14 '22 at 14:50
  • 1
    Is that the warning from your IDE or also a Sonar issue? If it's from the IDE, then it looks like there's some discrepancies in the rules. This seems like a false positive to me, so maybe it would be best to just suppress the Sonar warning? – QBrute Mar 14 '22 at 14:52
  • @QBrute Thanks a lot for your response. Sure will do the same. I have one more small doubt regarding the SonarLint, I have posted the same at the bottom of this question above. If possible can you please have a look and provide some suggestion? – BATMAN_2008 Mar 14 '22 at 15:02
  • @QBrute The issue is not coming from the IDE Problems rather my organization's SonarQube deployment. It's throwing as `bug`. I have added a screenshot of it in the question. Can you please once check and let me know how can I fix it? – BATMAN_2008 Mar 18 '22 at 10:18

0 Answers0