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

前端 未结 4 943
不知归路
不知归路 2021-01-07 16:14
List integer = Stream.generate(new Supplier() {
    int i = 0 ;

    @Override
    public Integer get() {
        return ++i;
    }
}).         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 17:09

    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.

提交回复
热议问题