I am currently preparing for an exam and am working on the following task:
Generate an infinite Stream containing the integers
(0, 1, -1, 2, -2, 3, -3, ...)
.
Following stream generate a normal infinite stream:
Stream<Integer> infiniteStream = Stream.iterate(1, i -> i + 1);
Is there a method or lambda expression that produces both positive and negative numbers?
We can create an infinite stream of any custom type elements by passing a function of a Supplier interface to a generate() method on a Stream.
Java Language Streams Infinite StreamsCalling a terminal method on an infinite Stream causes the Stream to enter an infinite loop. The limit method of a Stream can be used to limit the number of terms of the Stream that Java processes. This example generates a Stream of all natural numbers, starting with the number 1.
Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.
Something like this:
Stream<Integer> infiniteStream = Stream.iterate(1, i -> i > 0 ? -i : (-i + 1));
Or, if you wish to start with 0
:
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i > 0 ? -i : (-i + 1));
Of course, this can also be done with IntStream
:
IntStream infiniteStream = IntStream.iterate(0, i -> i > 0 ? -i : (-i + 1));
I want to provide an alternative to Erans answer.
Since you already know how the basic infinite stream works, you can use further stream operations like flatMap
to build upon it:
final Stream<Integer> eransAnswer = Stream.iterate(1, i -> i > 0 ? -i : (-i + 1));
final Stream<Integer> alternative = Stream.iterate(1, i -> i + 1)
.flatMap(i -> Stream.of(i, -i));
System.out.println(eransAnswer.limit(6).collect(Collectors.toList()));
System.out.println(alternative.limit(6).collect(Collectors.toList()));
Note that this only works if flatMap
is lazily evaluated. I put the limit
there so that I can collect it in some result (toList
), but it also works with the limit
after the flatMap
.
Sometimes, instead of putting the "complexity" into your generating formula, it may or may not make sense to split it up and use intermediate stream operations. If your thought process is that you alternate numbers, use Erans answer. If you rather think that for the infinite stream of natural numbers, you want to duplicate each number with its inverse, than the intention is conveyed more clearly with the alternative.
EDIT: To handle the Zero, you can do Stream.concat(Stream.of(0), alternative)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With