3.2.  Describe the Stream interface and pipelines

[Note]

Stream is a sequence of elements from a source supporting sequential and parallel aggregate operations. The source here refers to a Collection (e.g. java.util.List, java.util.Set) or an array which provides data to a Stream. The Stream keeps the order of the data as it is in the source.


List<String> list = Arrays.asList("Java", "is", "not", "great");
list.stream()
    .filter(s -> !s.startsWith("n"))
    .map(String::toUpperCase)
    .forEach(s -> System.out.print(s + " "));
}

					

output:

JAVA IS GREAT
					

A Collection (source) is an in-memory data structure to hold values and before we start using Collection, all the values should have been populated. Whereas a Stream is a data structure that is computed on-demand.

Stream does not store data, it operates on the source data structure (Collection or array) and produce pipelined data that we can use and perform specific operations. For example, we can create a Stream from a java.util.List and filter it based on a condition as shown above.

Intermediate Operations

Stream API operations that returns a new java.util.stream.Stream are called intermediate operations. Most of the times, these operations are lazy in nature, computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed. Intermediate operations are never the final result producing operations. Commonly used intermediate operations are filter and map.

Terminal Operations

Stream API operations that returns a result or produce a side effect. Once the terminal method is called on a stream, it consumes the stream and after that we can not use stream. Terminal operations are eager in nature i.e they process all the elements in the stream before returning the result. Commonly used terminal methods are forEach, toArray, min, max, findFirst, anyMatch, allMatch, etc. You can identify terminal methods from the return type, they will never return a Stream.

Stream Pipelines

To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of:

Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz