如何修复Sonarqube上的“不应不使用中间流方法”

我在 Sonarqube 上发现了这个错误:

private String getMacAdressByPorts(Set<Integer> ports) {
    ports.stream().sorted(); // sonar list show "Refactor the code so this stream pipeline is used"
    return ports.toString();
} //getMacAdressByPorts

我在网上找了很久,都没有用。请帮助或尝试提供一些想法如何实现这一目标。

回答

sorted()方法对Set你传入的没有影响;实际上,这是一个非终端操作,所以它甚至没有被执行。如果你想对你的端口进行排序,你需要像

return ports.stream().sorted().collect(Collectors.joining(","));

编辑:正如@Slaw 正确指出的那样,要获得与之前相同的格式(即[item1, item2, item3],您还需要将方括号添加到加入的收集器中,即Collectors.joining(", ", "[", "]")。为了简单起见,我将它们省略了。

  • Note to get the same output as typical implementations of `Set` the OP should use `Collectors.joining(", ", "[", "]")`.

以上是如何修复Sonarqube上的“不应不使用中间流方法”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>