带过滤器的IntStream迭代函数 [英] IntStream iterate function with filter

查看:102
本文介绍了带过滤器的IntStream迭代函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读这本书,名为《 现代Java的运用,我无法理解的一部分代码.

I was reading this book called Modern Java in Action and one part of code I could not comprehend.

      IntStream.iterate(0, n -> n + 4)
                .filter(n -> n < 100)
                .forEach(System.out::println);

作者说代码不会终止. 原因是无法在过滤器中知道数字继续增加,因此它会不断对它们进行无限过滤!

Authors says that code will not terminate. The reason is that there’s no way to know in the filter that the numbers continue to increase, so it keeps on filtering them infinitely!

我不知道原因.有人可以解释为什么.

I did not get the reason. Could someone explain it why.

推荐答案

作者说代码不会终止.

Authors says that code will not terminate.

是,因为

返回由迭代产生的无限顺序有序IntStream 将函数f应用于初始元素种子,从而产生 流由种子,f(种子),f(f(种子))等组成.

Returns an infinite sequential ordered IntStream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.

返回无限流,并且由于它是无限流,这意味着它只能通过某些操作终止.

returns an infinite stream and given it's an infinite stream it means it can only be terminated via certain operations.

鉴于此处使用的终端操作(forEach)并未短路,这意味着在这种特定情况下,您需要短路中间操作"来截断无限流,例如, limit(JDK8),takeWhile(JDK9)等.

Given the terminal operation in use here (forEach) is not short-circuiting it means that you require a "short-circuiting intermediate operation" to truncate the infinite stream in this specific case e.g. limit (JDK8),takeWhile (JDK9) et al.

JDK8中唯一的短路中间操作limit,因为它允许在无限时间内完成对无限流的计算.

The only short-circuiting intermediate operation in JDK8 is limit as it allows computations on infinite streams to complete in finite time.

原因是无法在过滤器中知道 数字继续增加,因此它继续过滤它们 无限!

The reason is that there’s no way to know in the filter that the numbers continue to increase, so it keeps on filtering them infinitely!

filter本身不是短路中间操作,因此无法终止流. filter的工作实质上是返回由与给定谓词相匹配的流元素组成的流.

filter itself is not a short-circuiting intermediate operation hence cannot terminate a stream. filter's job is essentially to return a stream consisting of the elements of the stream that match the given predicate.

结论:如果使用的无限流没有终端短路操作,则它需要短路中间操作来截断该流,否则该流将保持无限.

Conclusion: if one is using an infinite stream which does not have a short-circuiting terminal operation then it requires a short-circuiting intermediate operation to truncate the stream else the stream remains infinite.

这篇关于带过滤器的IntStream迭代函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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