How to Chain Stream Operations Together

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  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 ChainStreamOperations.java.
  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' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss