有什么办法可以阻止Stream.generate从其Lambda闭包中吗? [英] Is there any way to stop a Stream.generate from its Lambda closure?

查看:89
本文介绍了有什么办法可以阻止Stream.generate从其Lambda闭包中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Java 8和Lambda Expression,我很好奇我是否可以通过返回特定值来停止Lambda表达式内部的Stream生成 (如null). Stream.generate()可以做到这一点吗?

I just started playing around Java 8 and Lambda Expression and I am curious if I can stop the Stream generation from inside the Lambda expession by returning a specific value (like null). Is this possible with Stream.generate()?

private int counter;

private void generate()
{
    System.out.println(Stream.generate(() -> {
        if (counter < 10) {
            counter++;
            return RandomUtils.nextInt(100);
        } else {
            return null;
        }
    }).count());
}

不幸的是,此代码不会终止,因此只需返回null就不会退出流.

Unfortunately this code does not terminate, so by simply returning null will not step out of the stream.

推荐答案

Lamdas无法做到这一点,您无法从表达式内部控制流程. 甚至API文档都说Stream.generate生成无限流.

This is not possible with Lamdas, you cannot control the flow from inside the expression. Even the API docs says that the Stream.generate generates an infinite stream.

但是,您可以仅通过使用limit()方法来限制Stream并实现所需的功能:

However, you can limit the Stream and achieve the desired functionality simply by using the limit() method:

System.out.println(Stream.generate(() -> RandomUtils.nextInt(100)).limit(10).count());

这篇关于有什么办法可以阻止Stream.generate从其Lambda闭包中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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