Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #39014

Can I get the number where the stream stops

From Cecil Westerhof <Cecil@decebal.nl>
Newsgroups comp.lang.java.programmer
Subject Can I get the number where the stream stops
Date 2019-07-28 00:54 +0200
Organization Decebal Computing
Message-ID <87y30jnl62.fsf@munus.decebal.nl> (permalink)

Show all headers | View raw


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

Back to comp.lang.java.programmer | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Can I get the number where the stream stops Cecil Westerhof <Cecil@decebal.nl> - 2019-07-28 00:54 +0200
  Re: Can I get the number where the stream stops Andreas Leitgeb <avl@logic.at> - 2019-07-28 12:54 +0000

csiph-web