4 回答

TA贡献1877条经验 获得超6个赞
理想情况下,您不应该改变外部列表,而是可以使用Collectors.toList()将其收集到列表中:
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.collect(Collectors.toList()); // triggers the evaluation of the stream
System.out.println("Size = "+list.size());
在您的示例中,仅当终端操作像
allMatch()
anyMatch()
noneMatch()
collect()
count()
forEach()
min()
max()
reduce()

TA贡献1772条经验 获得超8个赞
由于您还没有完成流操作,即peek是一个中间操作。您必须使用终端操作才能继续执行。
建议:改为使用终端操作执行此类操作,例如collect
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.collect(Collectors.toList());
另外:添加一个peek帖子filter来观察值在观察中可能有点棘手,如下代码
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.peek(System.out::println) // addition
.collect(Collectors.toList());
输出看起来像:
one
two
two // filtered in
three
three // filtered in
four
five

TA贡献1752条经验 获得超4个赞
溪流是懒惰的。您可以调用终端操作,例如forEach
:
stream.peek(System.out::println) .filter(p1.or(p2)) .forEach(list::add);
如果您想peek
用作调试目的的中间操作,那么您必须在之后调用终端操作:
stream.peek(System.out::println) .filter(p1.or(p2)) .peek(list::add); .<any terminal operation here>();
顺便说一句,如果您只想将所有过滤后的值存储在一个列表中,那么最好使用collect(toList())
.

TA贡献1877条经验 获得超1个赞
您所做的一切filter
都是peek
设置一系列操作以应用于流。您实际上还没有使它们中的任何一个运行。您必须添加一个终端操作,例如count
. (另一个答案建议使用forEach
添加到列表中,但我认为您专门尝试使用中间操作peek
。)
添加回答
举报