Java 8 - What is a Stream ?


First, we obtain a stream from the list of transactions (the data) using the stream() method available on List. Next, several operations (filter, sorted, map, collect) are chained together to form a pipeline, which can be seen as forming a query on the data.




Streams  are the key abstraction in Java 8 for processing collections of values and specifying what you want to have done, leaving the scheduling of operations to the implementation. For example, if you want to compute the average of the values of a certain method, you specify that you want to call the method on each element and get the average of the values. You leave it to the stream library to parallelize the operation, using multiple threads for computing sums and counts of each segment and combining the results.

The key points of this chapter are:

  • Iterators imply a specific traversal strategy and prohibit efficient concurrent execution.
  • You can create streams from collections, arrays, generators, or iterators.
  • Use filter to select elements and map to transform elements.
  • Other operations for transforming streams include limit, distinct, and sorted.
  • To obtain a result from a stream, use a reduction operator such as count, max, min, findFirst, or findAny. Some of these methods return an Optional value.
  • The Optional type is intended as a safe alternative to working with null values. To use it safely, take advantage of the ifPresent and orElse methods.
  • You can collect stream results in collections, arrays, strings, or maps.
  • The groupingBy and partitioningBy methods of the Collectors class allow you to split the contents of a stream into groups, and to obtain a result for each group.
  • There are specialized streams for the primitive types int, long, and double.
  • When you work with parallel streams, be sure to avoid side effects, and consider giving up ordering constraints.
  • You need to be familiar with a small number of functional interfaces in order to use the stream library.

Comments