2

I thought if it was possible to create a stream which has a custom increment, like one only containing multiples of a given number (2 in this example). Is there a way to make this work?

IntStream.iterate(2, num -> (int) Math.pow(2, num))
AdHominem
  • 1,204
  • 3
  • 13
  • 32

1 Answers1

0

Multiples of a number? Shouldn't this work?

  IntStream.iterate(2, i -> i + 1)
            .filter(i -> i % 2 == 0)
            .limit(5)
            .forEach(System.out::println);
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Hmm this works but multiplicative values don't... my above solution doesn't yield squares of 2 but instead squares of the prior iteration which gives huge values.... am I missing something about the logic here? – AdHominem May 26 '16 at 18:55
  • @AdHominem it could be me missing the point of the question. This could be done in a much simpler way too : **IntStream.iterate(0, i -> i + 2).limit(5).forEach(System.out::println);**. In your example first number is 2 => 2 pow 2 = 4; then 2 pow 4 = 16, then 2 pow 16 = 65536 and so on. May be you could just post an example of what u want to achieve? – Eugene May 26 '16 at 19:02
  • Oh this doesnt work yet until Java 9's takeWhile comes... if you limit this stream, it will not limit the numbers but only the count of numbers. So If you want all squares of 2 up until 100 and you set limit(100), it will not stop at 100 but at 2^100. – AdHominem May 26 '16 at 19:19
  • @AdHominem until that is around there are other solutions to implement takeWhile here : http://stackoverflow.com/questions/20746429/limit-a-stream-by-a-predicate – Eugene May 26 '16 at 19:34
  • Are you trying to double the number each time? Maybe the increment could be simplified to `i -> i << 1`. Or multiples of 2? `i -> i + 2` – Hank D May 28 '16 at 06:14