Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Stream.limit work as expected in this snippet?

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?

like image 392
Vitaliy Avatar asked Dec 09 '15 07:12

Vitaliy


People also ask

How do you use Stream limits?

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.

What is stream method in Java?

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.


1 Answers

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.

like image 66
Eran Avatar answered Oct 11 '22 14:10

Eran