0

Consider the following series

0.5 1.5 4.5 13.5 40.5 121.5

We can generate this stream using tradional for loops. such as following

    float l = 0.5;
    for(int i=1;i<limit;i++)
    {
       if(i == 1 ) System.out.println(l+" ");
       float n = l+Math.pow(3,i-1);
       System.out.println(n+" ");
       l = n;
    }

This snippet works well. but java 8 streams has iterate functions to create such streams.

general syntax is Stream.iterate(0.5,f).limit().forEach(System.out::println);

But How will I access the previous element in the streams ? Also I need to track the i for the power of 3. Can anyone help ? Am I missing something?

  • See [this answer](https://stackoverflow.com/a/31650397/133203) for why streams are probably not the best abstraction if you care about the order of your elements. – Federico klez Culloca May 06 '20 at 07:39

1 Answers1

2

If I understand you correctly, you want to generate a stream where each element is the previous multiplied by 3:

0.5 1.5 4.5 13.5 40.5 121.5

To achieve this, you don't need to keep track of the previous element in the stream as you would do with a traditional for loop approach.

What you could do is to use DoubleStream.iterate() as you proposed. The method accepts a DoubleUnaryOperator as second argument, which is the method to apply when generating the stream. So in your case, this would be:

DoubleStream.iterate(0.5, d -> d * 3).limit(6).forEach(System.out::println);

This gives the following output:

0.5
1.5
4.5
13.5
40.5
121.5

limit(6) is important to limit the number of elements in the stream, otherwise you have to deal with infinity causing the stream to be consumed forever (or at least until an exception is thrown or an error raised). Not that the argument 6 is not the maximum value, but the number of elements in the stream.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
  • I got your Idea but is it possible to do it the way I described earlier ? –  May 06 '20 at 08:02
  • 1
    @AashishPawar This really is the way you should generate streams based on your requirement. I don't see any other way to do it with streams. – Magnilex May 06 '20 at 08:07