问题描述
我正在阅读有关Java流的短路操作的信息,并且在某些文章中发现skip()
是短路操作.
I am reading about Java streams' short-circuiting operations and found in some articles that skip()
is a short-circuiting operation.
在另一篇文章中,他们没有提到skip()
是短路操作.
In another article they didn't mention skip()
as a short-circuiting operation.
现在我很困惑; skip()
是不是短路操作?
Now I am confused; is skip()
a short-circuiting operation or not?
推荐答案
强调我的.
如果要在无限输入上调用skip
,则不会产生有限的流,因此不是短路操作.
if you were to call skip
on an infinite input it won't produce a finite stream hence not a short-circuiting operation.
JDK8 中唯一的短路中间操作是limit
,因为它允许无限流上的计算在有限时间内完成.
The only short-circuiting intermediate operation in JDK8 is limit
as it allows computations on infinite streams to complete in finite time.
示例:
如果要使用skip
执行该程序:
if you were to execute this program with the use of skip
:
String[] skip = Stream.generate(() -> "test") // returns an infinite stream
.skip(20)
.toArray(String[]::new);
它不会产生 finite 流,因此您最终将得到类似于"java.lang.OutOfMemoryError:Java堆空间"的内容.
it will not produce a finite stream hence you would eventually end up with something along the lines of "java.lang.OutOfMemoryError: Java heap space".
而如果您要使用limit
执行该程序,则会导致计算在finite
时间内完成:
whereas if you were to execute this program with the use of limit
, it will cause the computation to finish in a finite
time:
String[] limit = Stream.generate(() -> "test") // returns an infinite stream
.limit(20)
.toArray(String[]::new);
这篇关于skip()方法是短路操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!