.map 与 .peek - Intellij 建议

Dar*_*enn 6 java

collection.stream().map(x -> {
    if(condition) {
        x.setY(true);
    }
    return x;
}).collect(Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)

我有一个集合,我想在x满足某个条件时在变量中设置一些东西。我正在这样做,就像上面的代码中显示的那样。它完成了它的工作,并且有效。但是,IntelliJ 建议我.map.peek. 所以代码看起来像:

collection.stream().peek(x -> {
    if(condition) {
        x.setY(true);
    }
}).collect(Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)

它短了一行,但从我在 peek 文档中读到的:

API 注意:此方法的存在主要是为了支持调试,您希望在其中查看元素流经管道中的某个点时的情况:

那么,IntelliJ 的建议是否具有误导性?

Cod*_*Man 6

例子:

如果您在 java 8 中使用peek()with count()peek()会起作用,但如果您在 java 9 中使用它,除非您有filter(),否则它不会,因为count()在 java 9 中不会遍历所有元素。

你应该更喜欢forEachpeek

List<Integer> l = new ArrayList<>(Arrays.asList(1,2,3));
long c = l.stream().peek(System.out::println).count();
System.out.println(c);
Run Code Online (Sandbox Code Playgroud)

在 java 8 和 9 中尝试上面的代码,看看有什么不同。我的观点是您应该遵循 API 文档的说明并相应地使用它。