How to Create Infinite Streams in Java

Learn to generate an infinite stream of elements in Java. We will use Stream.generate() and Stream.iterate() methods to get infinite streams.

1. Overview

This is very important to note that Java Streams are lazy by design. So:

  • The generate() and iterate() methods are intermediate operations, so the actual element creation doesn’t begin until a terminal operation is invoked.
  • Be careful and use the limit() to restrict the number of elements in the stream, before invoking the terminal operation. Else the stream generation will continue infinitely.
  • Use iterate() method to create ordered stream elements, and generate() method to create unordered stream elements.

2. Infinite Streams with iterate() Method

2.1. Method Syntax

static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)

The Stream.iterate() method returns an infinite sequential ordered stream. The first element (index 0) in the Stream will be the provided 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.

2.2. Sequence of Integer Values

In the given example, we are creating an infinite stream of even numbers starting from 0. Then we collect the first 10 elements from the stream into a list.

List<Integer> ints = IntStream.iterate(0, i -> i + 2)
            .mapToObj(Integer::valueOf)
            .limit(10)
            .collect(Collectors.toList());

3. Infinite Streams with generate() Method

3.1. Method Syntax

static <T> Stream<T> generate(Supplier<T> s)

It 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.

3.2. Example – Stream of Random Numbers

The following example creates a stream of 10 random numbers between 0 and 99.

List<Integer> randomNumbers = Stream.generate(() -> (new Random()).nextInt(100))
                  .limit(10)
                  .collect(Collectors.toList());

3.3. Example – Stream of Custom Objects

The following example creates an infinite stream of employees and takes the first 5 employees from the stream.

List<Employee> employees = Stream.generate(Employee::create)
              .limit(5)
              .collect(Collectors.toList());

Where Employee class is this:

import java.io.Serializable;
import java.util.Random;

public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final Random r = new Random(Integer.MAX_VALUE);  

	private long id;
	private String name;
	private double salary;

	//All-args constructor, getters and setters are hidden for brevity

	public static Employee create() {
		//Get the employee id in more predictable manner
		//e.g. Max id present in databse + 1

		Employee obj = new Employee(r.nextInt(), "", 0.0d);
		return obj;
	}
}

4. Conclusion

In this Java Stream tutorial, we learned to create and operate on infinite streams. We learned to use the generate() and iterate() functions for creating bounded infinite streams with examples.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode