Java 8 generates stream of integers based on last value

I need to generate a stream of integers so that each value is based on the value specified earlier according to some math function.

For example, let's say I want to take the last number and add 10: [1, 11, 21, 31, 41, ...]

of course the actual function is much more complicated.

I tried to take a fibonacci example but couldn't get it to work:

Stream.iterate(new long[]{ 1, 1 }, p->new long[]{ p[1], p[0]+p[1] })
      .limit(92).forEach(p->System.out.println(p[0]));

      

I can only start with 1.

This is what I tried doing:

Stream.iterate(new long[]{ 1 }, p-> {p[0], p[0] + 10})
.limit(4).forEach(p->System.out.println(p[0]));

      

+3


source to share


3 answers


According to Stream#iterate

the docs method:

Returns an infinite sequential ordered stream created by iteratively applying function f to the initial seed, creating a stream of seed, f (seed), f (f (seed)), and so on.

The first element (position 0) in the stream will be the supplied seed. For n> 0, the element at position n will be the result of applying the function f to the element at position n - 1.

So, for your example, it should work like this:



Stream.iterate(1L, x -> x + 10L)
    .limit(4)
    .forEach(System.out::println); // 1 11 21 31

      

If your function is too complex, you can refer it to a method:

private long complexFunction(long value) {
    return <very_complex_calculation with value>;
}

long N = 4L;

Stream.iterate(1L, this::complexFunction)
    .limit(N)
    .forEach(System.out::println);

      

+3


source


If I don't get you wrong, you want something like this, you don't need any array long[]

.

LongStream.iterate(1, it -> it + 10).limit(8).forEach(System.out::println);

      

for Integer

you can use IntStream#interate

instead:

//                         v--- call your math function here
IntStream.iterate(1, it -> math(it, ...)).limit(8).forEach(System.out::println);

      



OR using LongStream#range

instead:

LongStream.range(0,8).map(it -> 10*it + 1).forEach(System.out::println);

      

Output

[1, 11, 21, 31, 41, 51, 61, 71]

      

+1


source


You can use AtomicLong to store another variable while iterating. For a Fibonacci sequence, where you would store the largest of the two numbers, both in AtomicLong and the iteration variable would be the smallest. For example.

AtomicLong fibonacci = new AtomicLong(1);
Stream.iterate(1L, x -> fibonacci.getAndAdd(x))
    .limit(10)
    .forEach(i -> System.out.println(fibonacci.get()));

      

+1


source







All Articles