Java generate stream

Learn to create or generate a finite stream of elements using java.util.Stream API. Also learn to generate infinite stream of data/elements.

1. How to generate streams

In Java, the following static methods are used to create Stream objects of type T :

static <T> Stream<T> of(T... values);
static <T> Stream<T> generate(Supplier<? extends T> s);
  • The first method creates a stream by providing a variable-length list of values e.g. Stream.of(1, 2, 3, 4).
  • The second method accepts a Supplier that provides an infinite series of elements which are placed in the stream. The limit() method can then be called in the stream chain to stop the series after a certain number of elements.

2. Java generate finite streams

The following are the examples to better understand how to create a stream of finite number of elements.

2.1. Finite stream of Integers

Stream<Integer> numbers = Stream.of(1, 2, 3, 4);

2.2. Finite stream of Strings

Stream<String> alphabets = Stream.of("A", "B", "C", "D");

2.3. Finite stream of objects

private static Employee[] arrayOfEmps = {
    new Employee(1, "Jeff Bezos", 100000.0), 
    new Employee(2, "Bill Gates", 200000.0), 
    new Employee(3, "Mark Zuckerberg", 300000.0)
};

Stream<Employee> employees = Stream.of(arrayOfEmps);

3. Java generate infinite streams

The following are the examples to learn to create a stream of infinite data/elements. The first example creates a stream of 10 random numbers between 0 and 99.

Stream<Integer> randomNumbers = Stream.generate( () -> (new Random()).nextInt(100) );

randomNumbers.limit(20).forEach( System.out::println ); //print first 20 numbers

A similar example to generate infinite stream of even numbers starting from 0.

Stream<Integer> infiniteEvenNumbers = Stream.iterate(0, n -> n + 2);

infiniteEvenNumbers.limit(10).forEach( System.out::println ); //print first 10 numbers

4. Conclusion

In this Java 8 stream tutorial, we learned to finite stream elements as well as infinite stream of data/elements. We saw the usage of limit() function which is used to pick first N elements from an infinite stream.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.