Java Streams

Infinite Streams

March 14, 2020

With finite or Bounded streams we supply elements up to ceratin stream length. Whereas, in infinite streams, we don’t have any stream length.

Ways of creating infinite streams:

  • Stream<T> iterate(T seed, UnaryOperator<T> f): iterate() method of Stream returns an infinite sequential ordered stream. It takes a seed and UnaryOperator.
public class InfiniteStreams {

	public static void main(String[] args) {
		
            //Takes Integer Seed and UnaryOperator
		Stream.iterate(0, i -> i-1)
		.limit(15)
		.forEach(System.out::println);
         }
}
//output
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14

Seed is the first element of the stream. Initially, it is also the input to the function and then the operation is performed on it, we get the second element.

Now in the next step, this second element becomes the input to the function. We get the 3rd element and this goes on. There is no end to it.

  1. Seed = 0
  2. (0, 0 -> 0 – 1) = -1
  3. (-1, -1 -> -1-1) = -2
  4. ..so on

We have this iterate method in Stream class as well as in the primitive  Streams classes.

  • Stream<T> generate(Supplier<? extends T> s): generate() method of Stream returns an infinite sequential unordered stream where each element is generated by the provided supplier. It takes a supplier to supply elements.
      //Takes Supplier
		Stream.generate(()->"Hello")
		.forEach(System.out::println);

This will print “Hello” infinite times!

This method is suitable when we want a stream of Random Numbers. And also, this method is present in all numeric streams.

 public class InfiniteStreams {

	public static void main(String[] args) {
		
		Stream.generate(new Random()::nextInt)
 		.forEach(System.out::println);
	}
}
//Output
876490064
-2101752723
-1604859388
517997883
2139721178
1699468601
-1762600162
-642991668
460154128
2089927652
1883319990
735603930
......