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

Bat*_*rie 0 java 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
Run Code Online (Sandbox Code Playgroud)

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

dan*_*niu 5

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

return ports.stream().sorted().collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,要获得与 `Set` 的典型实现相同的输出,OP 应使用 `Collectors.joining(", ", "[", "]")`。 (2认同)