Now that Java 8 supports passing behavior as a parameter, the stream programming paradigm can be leveraged where it was previously non-trivial to do so.
What is a Stream?
The concept of a stream in the field of computing simply refers to processing a collection of data. Imagine you are working with a list of strings (in any language):
A stream is a mechanism to process this list, explicitly defining a series of actions to take on the collection (such as printing each string). Any programming language that defines a stream API will implement various actions that align with the goals of general collections processing. For instance, a stream API may offer a way to calculate the average of a collection of numbers, or facilitate conversion from one collection type to another (for instance, convert a map to a list). Sometimes actions in a stream are ‘pipelined’, such that the results of one are utilized by a subsequent action.
Using the Java 8 Stream API
In Java 8, the stream API contains a blend of useful out-of-the-box tools, in addition to facilities for creating your own stream actions. Below are some examples of using Java 8 streams.
Our first stream API example involves printing out a list of strings:
Check out our lambda expressions blog post to learn more about how behavior parameterization with lambda expressions work. While this example could be further simplified with a method reference, we are focusing here on the streams component of Java 8.
An out-of-the-box capability of the streams API is calculating the average of a collection:
The capabilities of the Java 8 stream API extend much further than what was covered here. To gain a more substantial understanding of the stream API, check out Processing Data with Java SE 8 Streams, Part 1, by Raoul-Gabriel Urma. In addition, you can discover the available stream operations by reading over the Java 8 stream API documentation.
You’ll find that approaching collections processing with a stream mindset will accelerate your development. Your code will become shorter and easier to comprehend. Monotonous tasks like collections filtering or sorting come out-of-the-box, allowing you to focus on your problem domain.
If you are working in a Java 8 environment, it would behoove you to take advantage of the newest features, like the stream API. Simplify your development; go with the flow.