为什么Stream.limit在此代码段中没有按预期工作? [英] Why doesn't Stream.limit work as expected in this snippet?

查看:164
本文介绍了为什么Stream.limit在此代码段中没有按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

根据我的预期,收取电话永远不会回来在过滤器之前设置 limit 会产生预期结果。为什么?

Counter to my expectation, the collect call never returns. Setting limit before filter produces the expected result. Why?

推荐答案

由于只有4个元素通过过滤器, limit(10)永远不会达到10个元素,因此Stream管道不断生成新元素并将它们提供给过滤器,尝试达到通过过滤器的10个元素,但由于只有前4个元素通过过滤器,因此处理永远不会结束(在至少 i 溢出)。

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

Stream管道不够聪明,知道没有更多的元素可以通过过滤器,因此它继续处理新元素。

The Stream pipeline is not smart enough to know that no more elements can pass the filter, so it keeps processing new elements.

这篇关于为什么Stream.limit在此代码段中没有按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆