java:S6204 Suggestion of using .toList() in a List that is from the interface does not compile

Sonar is constantly asked to use .toList() in addition to .collect(Collectors.toList()) but in some cases this request is wrong as the solution simply won’t compile.

Here’s a small example:

public interface TestSonar {

}


@RequiredArgsConstructor
public class ReturnTestSonar {
    @Getter private final List<TestSonar> list;
    
    @RequiredArgsConstructor
    public static class TestSonarImpl implements TestSonar {
        @Getter private final Integer integer;
    }

}


public class SonarViolation {
        
    public List<TestSonar> teste(List<Integer> list) {
        return list.stream().map(TestSonarImpl::new).collect(Collectors.toList());
    }
    
    public ReturnTestSonar myList(List<Integer> list) {
        return new ReturnTestSonar(list.stream().map(TestSonarImpl::new).collect(Collectors.toList())); 
    }
}

Hello @Irineu_Ruiz, thanks for reaching out.

I assume you are getting the issues raised on the following lines:

return list.stream().map(TestSonarImpl::new).collect(Collectors.toList());

and

return new ReturnTestSonar(list.stream().map(TestSonarImpl::new).collect(Collectors.toList())); 

Can you confirm it?

In these cases, the rule is valid and you should replace the .collect(Collectors.toList()); with .toList();. The compliant code will be the following:

return list.stream().map(TestSonarImpl::new).toList();

and

return new ReturnTestSonar(list.stream().map(TestSonarImpl::new).toList()); 

I hope this helps you, and in case I’m missing something don’t hesitate to let me know.

Cheers