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()));
}
}