DEV Community

Lucas Stoller
Lucas Stoller

Posted on • Originally published at theright.dev on

What is Java Stream and why does it exist?

A Stream is a sequence of values. The java.util.stream package defines types for streams of reference values (Stream) and some primitive values (IntStream, LongStream, and DoubleStream).

Streams are like iterators in the way they supply their elements as needed for processing.

Streams were introduced in Java 8 as a way to add manageability to existing data structures. With them, we can use some very interesting methods for our structures:

  • Map

  • Reduce

  • Filter

  • Find

  • Foreach

  • Among others.

For this, it is important to create a stream pipeline. A stream pipeline is used to manage actions on a stream. It is composed of iterators and finalizers, where iterators are methods that return stream and finalizers do not return streams and still close it. Example:

To use Java streams we need to convert the data structure we are working on to a Stream, assemble and run our pipeline. Finally, we can convert the stream pipeline output back to the source structure if necessary.

You might be wondering: "Why weren't such methods declared directly in the data structures?"

As you can see, we need to convert the structure we are working on to a stream before using the utility methods because they are not present in the Collections API but have been externalized in their own Streams API. And these are some of the reasons why Java Architects proposed this solution:

  1. The Collections API is more concerned with storing the data than with the actions and work that we are going to do on the data itself;

  2. Manipulation X Management of the Data Structure

  3. Eager Loading X Lazy Loading

  4. Even though those methods we declared in Collections API we would still need to do a conversion to work with asynchronous processing, see:

  5. The risk of collision in method names increases every time we insert a new method in an API with hierarchically ordered classes.

Top comments (0)