【问题标题】:SONAR: Replace this lambda with a method referenceSONAR:将此 lambda 替换为方法引用
【发布时间】:2016-05-26 17:19:29
【问题描述】:

我在 Sonar 上收到以下警告:

用方法引用替换这个 lambda

代码是:

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

我怎样才能克服这个警告?

【问题讨论】:

  • 对于这个明显错误的警告我无话可说,但整个 Stream 的使用与该 API 的目的背道而驰。如果您只想通过forEach 执行操作,只需在集合上调用forEach。在任何一种情况下,您都不需要检查空集合。如果您只使用CollectionUtils.isEmpty 进行null 测试,则应改为执行干净的null 检查。但实际上,您想使用return testIds.stream().map(id -&gt; getTest(id)) .collect(Collectors.toList()); 而不是使用forEach那么你确实可以使用getTest的方法参考
  • 作为 SonarQube 的 java 分析器的开发人员:警告确实是错误的,但您能否准确说明您使用的是哪个版本的 java 分析器?因为这很可能在最新版本中得到修复?

标签: lambda java-8 sonarqube


【解决方案1】:

您可以将您的getTest 标记为static,并使用如下引用编写您的方法:

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

【讨论】:

  • 请注意,您不需要像ArrayList&lt;Test&gt;::new 中的显式类型,您可以简单地使用ArrayList::new。除此之外,CollectionUtils.isEmpty(testIds) 已过时,Stream API 将处理空列表,因此,CollectionUtils.isEmpty 测试只是一个混淆的null 测试。所以 if 是有意的,if(testIds==null) return new ArrayList&lt;&gt;(); 说明了这一点。或者,您可以使用return (testIds==null? Stream.&lt;String&gt;empty(): testIds.stream()) .map(…) .collect(…);,这样可以根据需要更轻松地更改返回的List 类型,例如使用Collectors.toList()
猜你喜欢
  • 2018-12-26
  • 2018-12-14
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
相关资源
最近更新 更多