Is the skip() method a short circuiting-operation?

  • A+
Category:Languages

I am reading about Java streams' short-circuiting operations and found in some articles that skip() is a short-circuiting operation.

In another article they didn't mention skip() as a short-circuiting operation.

Now I am confused; is skip() a short-circuiting operation or not?

 


From the java doc under the "Stream operations and pipelines" section :

An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.

Emphasis mine.

if you were to call skip on an infinite input it won't produce a finite stream hence not a short-circuiting operation.

The only short-circuiting intermediate operation in JDK8 is limit as it allows computations on infinite streams to complete in finite time.

Example:

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); 

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".

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); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: