Java guides

How to start using Java streams

Start using Java streams and make your life easier

Crimson
Nerd For Tech

--

Streams were introduced in Java 8, they are essentially sequences of elements that support aggregate operations, and they are similar to loops.

Suppose we want to count the number of times the word “key” appears in this array:

Using for loops, we would get something like this:

And using streams, we would get something like this:

As you can see, the method names from the stream tell you right away what the code intends to do. First, we convert our array into a sequential stream with the Arrays stream() method, then the filter method is used to return a stream fulfilling the condition indicated in the lambda expression (a -> a.equals(“key”)), the number of elements in the stream is returned by the count() method.

The features of Java streams are:

  • Streams don’t store their elements. These are stored in a collection or generated in demand.
  • Since streams are not data structures, you’ll need to take the input from I/O channels, arrays, or collections.
  • Streams do not modify the original data structure.
  • Streams do not mutate their source. Instead of removing elements or modifying the stream, the filter method from the previous example results in a new stream.
  • Stream operations are not executed until their result is needed, in other words, they are lazy.

Streams intermediate and terminal operations

After creating a stream you’ll normally use intermediate and terminal operations.

  • Intermediate operations are used to transform the original stream. The filter() method used in the previous example is an intermediate operation, it yields a stream that contains the elements fulfilling a condition.
  • Terminal operations force the execution of the lazy operations that precede them. These operations return a void or a non-stream result instead of another stream. The count() method from the previous example is a terminal operation. After using a terminal operation the stream can no longer be used.

Let’s take a look at the following example:

This code multiplies each number from the array by three and then prints it. Here the map() method is used to return a stream after applying the (a -> a * 3) function to the original stream, this is an intermediate operation. The for Each() method performs an action for each element in the stream and is a terminal operation.

Streams are an extremely useful tool that can save your time and make your code a lot more readable. Start implementing this API in your code and get stuff done simply.

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

--

--