List<Integer> integer = Stream.generate(new Supplier<Integer>() { int i = 0 ; @Override public Integer get() { return ++i; } }).filter(j -> j < 5) .limit(10) // Note the call to limit here .collect(Collectors.toList());
Counter to my expectation, the collect
call never returns. Setting limit
before filter
produces the expected result. Why?
IntStream limit() method in JavaThe limit() method of the IntStream class is used to return a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. Here, maxSize is the parameter. Here, the maxSize parameter is the count of elements the stream is limited to.
A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.
Since there are only 4 elements that pass the filter, limit(10)
never reaches 10 elements, so the Stream pipeline keeps generating new elements and feeding them to the filter, trying to reach 10 elements that pass the filter, but since only the first 4 elements pass the filter, the processing never ends (at least until i
overflows).
The Stream pipeline is not smart enough to know that no more elements can pass the filter, so it keeps processing new elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With