Java guides

Creating streams with java

Understanding the most common methods used to create streams

Crimson
Nerd For Tech

--

Streams are pretty simple to create if you understand these methods. You’ll usually create streams from arrays, but you can also create infinite streams, empty streams, and even streams from an object.

Create a stream from an array

To create a stream from an array, you can use both Arrays.stream() and Stream.of() methods. These methods work in different ways:

  • Arrays.stream() accepts an array as a parameter and returns a sequential stream. To create double, long, and integer arrays you’ll need to use the IntStream, DoubleStream, and DoubleStream classes.
  • Stream.of() accepts one or more values as parameters, these values will be included in the new stream.

Creating a simple stream using both methods:

Creating double, long, and integer streams from arrays using the Arrays.stream() method:

Using the Arrays.stream(T[] array, int startInclusive, int endExclusive) method, you can create a stream from a part of an array:

And that’s how you create streams from arrays, you can also use the following methods to create streams: IntStream.of(), LongStream.of(), and DoubleStream.of(), these methods are used to create integer, long and double streams and they work like the Stream.of() method.

The generate() and iterate() methods

These two methods work in the following way:

  • The generate(Supplier<T> s) method creates infinite streams generated by the supplier. This is easier to understand if we look at an example:

If you want to create a finite stream use the limit() method:

  • The iterate(T seed, Predicate hasNext, UnaryOperator next) method is used to apply the operation next to the seed if the hasNext condition is true. Here we are using this method to multiply a number by n until the number is greater than 100:

This method can also yield infinite streams if you don’t provide a predicate.

The empty() and ofNullable() methods

These two methods are easy to understand:

  • The empty() method, as you can imagine, returns a stream with no elements.
  • The ofNullable(T t) accepts a single element as a parameter, if the element is null, the stream will be empty, otherwise, the method will return a stream with a single element.

Thanks for reading this article! Leave a comment below if you have any suggestions. Be sure to clap this post and follow me.

--

--