A terminal operation in Java is a method applied to a stream as the final step. Additional stream operations are not permitted because a terminal operation never produces a stream object. A common example of a terminal operation is the forEach
method that often is used to print the stream object's elements. Another useful example is the reduce
method that produces a single result (e.g., a sum) from a stream. Other good examples include min
and max
. The following four steps show how to work with stream terminal operations.
Take our Introduction to Java Training course for free.
See the Course Outline and Registerimport java.util.stream.*;
import java.util.*;
public class WorkingWithTerminalOperations {
private static List numbers=new ArrayList<>();
static {
numbers.add(50);
numbers.add(1);
numbers.add(204);
numbers.add(-27);
numbers.add(27);
numbers.add(-204);
numbers.add(9);
numbers.add(40);
}
public static void main (String args[]) {
System.out.println("The array list integers: ");
numbers.stream().forEach(System.out::println);
Optional min=numbers.stream().min(Integer::compare);
System.out.println("Minimum value: " + min.get());
Optional max=numbers.stream().max(Integer::compare);
System.out.println("Maximum value: " + max.get());
Optional total=numbers.stream().reduce((i,j)-> i+j);
System.out.println("Sum: " + total.get());
}
}
forEach
, and this operation will print each element of the stream. Next, the min
operation is called. This method returns the minimum value stored in the stream as an Optional
. Optional
is a new class in Java 8 that provides a get
method to return the value of the variable if the value is non-null. The next operation is max
. This method returns the maximum value stored in the stream. Finally, the reduce
method is called. The parameter passed to this method is a lambda expression. In this case, the expression adds one element to the next element, accumulating a total that is returned as an Optional
. I have highlighted the terminal operations in the image below:WorkingWithTerminalOperations.java
.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, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.
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.