How to Chain Stream Operations Together
The Stream class was introduced in Java and supports a variety of methods to process a stream. The methods can be chained together, reducing the number of source statements and the need for intermediate variables. In addition, many types of process flow can be implemented. To learn how to chain stream operations together, follow these four steps.
- Open your text editor and create a new file that will contain the Java source. Type in the following Java statements:
The stream will be created from the ArrayList that is defined on line 4. Note that a static block is used to add elements to the ArrayList. A static block is executed one time when the program is loaded into memory. Line 14 contains the statement that demonstrates chaining together stream operations. The
streammethod returns a stream. The stream is then passed to the
filtermethod. This method returns a stream whose elements satisfy the search criteria, i.e., musical instruments whose names begin with "T". The stream that is output from the filter operation is passed to the
forEach. This method iterates through each element and applies the operation specified, which in this case is
System.out.println. Therefore, each element will be displayed on the console.
- Save your file as
- Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter.
- You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter. The output displays the musical instruments whose names begin with "T", the end result of the chained stream operations.