有没有一种方法可以检查流在Java中是否有限? [英] Is there a way to check whether a stream is finite in Java?

查看:96
本文介绍了有没有一种方法可以检查流在Java中是否有限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java中存在无限个流.

I know there is infinite stream in Java.

是否可以检查流是否有限?

类似于这种方法isStreamFinite(Stream<T> stream)?

@Test
public void testStreamFinity() {
    assertFalse(isStreamFinite(generateLong()));
}

private <T> boolean isStreamFinite(Stream<T> stream) {
    if (stream.count() < Long.MAX_VALUE) {
        return true;
    }
    return false;
}

private Stream<Long> generateLong() {
    return LongStream.generate(() -> new Random().nextLong()).boxed();
}

的构造会留下一些标记/轨道,我们可以使用这些标记/轨道进行追溯以对其进行检查?

The construction of the Stream would leave some marks/tracks that we can use to trace back to check it?

检查方法是否可以始终可靠地按预期工作?

The checking method could work always as expected reliably?

在尝试通过检测流的isFinite解决问题时,我对此有误.所提到的答案似乎并不稳定/可靠.我将在其他地方重构我的解决方案.谢谢你的帮助〜

I was wrong about this when trying to solve a problem by detecting the isFinite of a stream. It seems it's not stable/reliable as the answers mentioned. I will refactor my solution in another around. Thank you for the help ~

推荐答案

没有可靠的方法.甚至使用记录在案的estimateSize:

There is no reliable way to do it. Even using the estimateSize, which is documented:

...,如果无穷大,未知或计算成本过高,则返回Long.MAX_VALUE.

... or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute.

因此,仅仅依靠Long.MAX_VALUE会告诉您此流是否无限的事实是完全错误的.

So simply relying on the fact that Long.MAX_VALUE will tell you if this stream is infinite or not - is simply wrong.

另一个建议是使用SIZED,这又是错误的:

The other suggestion says that to use SIZED, which is again wrong:

IntStream.generate(() -> 1).limit(5)

知道这是一个SIZED流,该实现不会并且将报告大小标志.

You know that this is a SIZED stream - the implementation does not and will not report the sized flag.

底线:您无法以可靠的方式.从理论上讲,在某些情况下这是可能的,例如当您 just 使用generate而不限制或短路流时,实现可以注册一个标志,例如IS_INFINITE之类的东西,但是此IMO将没有用,可能在99%的情况下都是如此.

Bottom-line: you can't in a reliable way. Theoretically this could be possible for some cases, like when you just use generate without limiting or short-circuiting the stream, the implementation could register a flag like IS_INFINITE or something, but this IMO would be useless, probably for 99% of the cases.

您还可以在这里反向思考,如果您想确定地确定此流是否有限,那又如何呢?在这种情况下,getExactSizeIfKnown()会告诉您.

You can also think in reverse here, how about when you want to tell with certainty if this stream is finite? In such a case, getExactSizeIfKnown() would tell you that.

这篇关于有没有一种方法可以检查流在Java中是否有限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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