JDev
JDev

Reputation: 1822

SONAR: Replace this lambda with a method reference

I am getting following warning on Sonar:

Replace this lambda with a method reference

Code is :

protected List<Test> getTests(List<String> testIds) {
    List<Test> tests = new ArrayList<>();
    if (!CollectionUtils.isEmpty(testIds)) {
        testIds.stream().forEach(eachTestId -> tests.add(getTest(eachTestId)));
    }
    return tests;
}

How can I get over this warning?

Upvotes: 3

Views: 3524

Answers (1)

Jude Niroshan
Jude Niroshan

Reputation: 4460

You could mark your getTest as static and write your method with using references as follows:

protected List<Test> getTests(List<String> testIds) {

    if (CollectionUtils.isEmpty(testIds)) {
          return new ArrayList<Test>();
    }

    return testIds.stream()
          .map(Test::getTest)
          .collect(Collectors.toCollection(ArrayList<Test>::new));
}

Upvotes: 1

Related Questions