Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Cecil Westerhof Newsgroups: comp.lang.java.programmer Subject: Can I get the number where the stream stops Date: Sun, 28 Jul 2019 00:54:13 +0200 Organization: Decebal Computing Lines: 36 Message-ID: <87y30jnl62.fsf@munus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="193878f30de6283201fc687c2b428d6b"; logging-data="2261"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/Qq4c76Doyn0d+bgqlxYwjYcu7syvqtos=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/25.1 (gnu/linux) Cancel-Lock: sha1:TWxGxTZ146hDnvUwqdN45LwSlBw= sha1:Y2Fet22ZU96ZgSanMhuytI0bT0c= Xref: csiph.com comp.lang.java.programmer:39014 To play with streams I wrote the following stream to get a Fibonacci Number: long fibonacciStream(int n) { return Stream. iterate(new long[]{0, 1}, t -> t[1] > 0, t -> new long[]{t[1], t[0] + t[1]}). skip(n). map(t -> t[0]). findFirst(). get(); } This works like a charm as long as 0 <= n < 92. When it is called with 92 I get: java.util.NoSuchElementException thrown: No value present Is there a way to get the value for which the stream does not work anymore? For example if called with: fibonacciStream(121); I would like an exception that says that it cannot be called with values above 91. In this case I could use: Stream. iterate(new long[]{0, 1}, t -> t[1] > 0, t -> new long[]{t[1], t[0] + t[1]}). count() And when n greater or equal generate an exception. But that works because calculating the count is an inexpensive operation. How to solve it when it is an expensive operation? Or do I want to much? ;-) -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof