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.

  1. Open your text editor and create a new file that will contain the Java source. Type in the following Java statements:
    Java Source for Chained Operations
    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 stream method returns a stream. The stream is then passed to the filter method. 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.
  2. Save your file as
  3. 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.
    Compile Chained Operations
  4. 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.
    Run Program with Chained Operations
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.